【问题标题】:How do I add a string to my array of type struct which contains both strings and ints in c++?如何将字符串添加到包含 c++ 中的字符串和整数的结构类型数组?
【发布时间】:2019-03-14 06:43:26
【问题描述】:

这些是我的结构:

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;

说没有操作符 >> 匹配这些操作数。 操作数类型为:std::string >> std::string

我试图放入结构数组的数据也来自一个包含以下信息的文本文件:

完美

艾德希兰和碧昂丝

英格兰

4

23

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

【问题讨论】:

    标签: c++ arrays struct


    【解决方案1】:

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

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

    或者直接读入结构体:

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

    使用&gt;&gt; 读取会从输入中读取一个单词,因此它仅适用于您的数字。要读取完整的行(字符串),请使用std::getline

    【讨论】:

      【解决方案2】:

      &gt;&gt; 运算符有两种含义:

      • 左右移位
      • 将输入从流中读取到对象中

      这里使用后一种含义。如您所见,定义说“从流”和“到对象”。

      在您的代码中,您调用 &gt;&gt; 运算符将“从字符串”s[count].Title 读取到另一个字符串 title

      预定义的&gt;&gt; 运算符有许多变体。它们都有一个流作为第一个操作数。因此,要使用它们,请使用std::cin &gt;&gt; s[count].Title

      如另一个答案中所述,&gt;&gt; 运算符在第一个单词后停止复制。因此最好使用std::getline(std::cin, s[count].Title)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-09
        • 2021-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-19
        • 1970-01-01
        相关资源
        最近更新 更多