gpt4 book ai didi

c++ - 如何将字符串添加到我的结构数组中,该数组在 C++ 中同时包含字符串和整数?

转载 作者:行者123 更新时间:2023-11-30 04:50:02 25 4
gpt4 key购买 nike

这些是我的结构:

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++;
}

我在这三行中遇到错误:

    s[count].Title >> title;
s[count].ArtistDetails.Name >> name;
s[count].ArtistDetails.CountryOfOrigin >> country;

Saying no operator>> 匹配这些操作数。操作数类型为:std::string >> std::string

此外,我尝试放入结构数组的数据来自包含以下信息的文本文件:

完美

艾德·希兰与碧昂丝

英国

4

23

如果重要的话,文本文件名是 songdata.txt。非常感谢任何帮助!

最佳答案

您可以使用= 运算符来赋值。

input >> minutes;
s[count].LengthOfSong.Minutes = minutes;

或者直接读入结构体:

input >> s[count].LengthOfSong.Minutes;

Reading with >>> 从输入中读取一个单词,因此它只适用于您的数字。要读取完整的一行(字符串),请使用 std::getline .

关于c++ - 如何将字符串添加到我的结构数组中,该数组在 C++ 中同时包含字符串和整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55156432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com