簡體   English   中英

如何將字符串添加到我的 struct 類型數組中,該數組同時包含 C++ 中的字符串和整數?

[英]How do I add a string to my array of type struct which contains both strings and ints in c++?

這些是我的結構:

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;

說 no operator >> 匹配這些操作數。 操作數類型是: std::string >> std::string

此外,我試圖放入 struct 數組的數據來自包含以下信息的文本文件:

完美的

艾德希蘭與碧昂斯

英國

4

23

如果重要的話,文本文件名是songdata.txt。 任何幫助是極大的贊賞!

您可以使用=運算符來賦值。

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

或者直接讀入結構體:

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

使用>>讀取從輸入中讀取一個單詞,因此它僅適用於您的數字。 要讀取完整行(字符串),請使用std::getline

>>運算符有兩個含義:

  • 移位位
  • 將流中的輸入讀入對象

這里使用后一種含義。 如您所見,該定義表示“來自流”和“到對象”。

在您的代碼中,您調用>>運算符將“從字符串” s[count].Title到另一個字符串title

預定義的>>運算符有許多變體。 它們都有一個流作為第一個操作數。 因此,要使用它們,請使用std::cin >> s[count].Title

如另一個答案中所述, >>運算符在第一個單詞后停止復制。 因此最好使用std::getline(std::cin, s[count].Title)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM