Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将字符串添加到我的struct类型数组中,该数组在c++;?_C++_Arrays_Struct - Fatal编程技术网

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;