C++ 如何将字符串添加到我的struct类型数组中,该数组在c++;?
这些是我的结构:C++ 如何将字符串添加到我的struct类型数组中,该数组在c++;?,c++,arrays,struct,C++,Arrays,Struct,这些是我的结构: struct Artist { string Name; string CountryOfOrigin; }; struct Time { int Minutes; int Seconds; }; struct Song { string Title; Artist ArtistDetails; Time LengthOfSong; }; 我的职能是: void LoadSongDataFromFile(Song
struct Artist
{
string Name;
string CountryOfOrigin;
};
struct Time
{
int Minutes;
int Seconds;
};
struct Song
{
string Title;
Artist ArtistDetails;
Time LengthOfSong;
};
我的职能是:
void LoadSongDataFromFile(Song s[])
{
string inputFile, title, name, country;
int minutes, seconds;
cout << "Please enter the input file name: ";
cin >> inputFile;
ifstream input;
input.open(inputFile);
int count = 0;
while (input >> title)
{
s[count].Title >> title;
s[count].ArtistDetails.Name >> name;
s[count].ArtistDetails.CountryOfOrigin >> country;
s[count].LengthOfSong.Minutes >> minutes;
s[count].LengthOfSong.Seconds >> seconds;
count++;
}
说“无操作员>>与这些对手相匹配。
Opperand类型是:std::string>>std::string
另外,我试图放入struct数组的数据来自包含以下信息的文本文件:
完美的
埃德·希伦和碧昂丝在一起
英格兰
四,
二十三
如果有必要,文本文件名为songdata.txt。非常感谢您的帮助 您可以使用
=
运算符分配值
input >> minutes;
s[count].LengthOfSong.Minutes = minutes;
或直接读入结构:
input >> s[count].LengthOfSong.Minutes;
使用
>
阅读从输入中读取一个单词,因此它只适用于您的数字。要读取完整的行(字符串),请使用。运算符有两种含义:
- 移位
- 将输入从流读入对象
>
操作符来读取“从一个字符串”s[count]。Title
到另一个字符串Title
预定义的>>
运算符有许多变体。它们都有一个流作为第一个操作数。因此,要使用它们,请使用std::cin>>s[count].Title
如另一个答案所述,>
操作员在第一个单词后停止复制。因此,最好使用std::getline(std::cin,s[count].Title)
input >> s[count].LengthOfSong.Minutes;