C++ cin.get() 结构

C++ cin.get() structs

下面是概要: 我正在使用结构创建一个小型音乐库。图书馆有几个功能,其中之一是我应该能够将新歌曲添加到图书馆。我必须使用 cin.get() 并从那里开始,但每次我执行它时,它都会进入无限循环。这是我的添加歌曲功能的代码。整数 i 只是一些索引值。

struct song {
    char title[50];
    char artist[50];
    char minutes[50];
    char seconds[50];
    char album[50];
}info[50];
void new_song(int& i)
int main(){
}
new_song(i);
{
    cin.get(info[i].title,50,'\n');
    cin.ignore(100, '\n');
    cin.get(info[i].artist, 50, '\n');
    cin.ignore(50, '\n');
    cin.get(info[i].minutes, 50, '\n');
    cin.ignore(50, '\n');
    cin.get(info[i].seconds, 50, '\n');
    cin.ignore(50, '\n');
    cin.get(info[i].album, 50, '\n');
    cin.ignore();
}

任何帮助都有帮助。

我可能会这样做而不是使用 cin.get()、C 字符串和静态数组:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct Song {
   string title;
   string artist;
   string minutes;
   string seconds;
   string album;
};

void add_song_from_stdin(vector<Song> &songs) {
   Song s;
   getline(cin, s.title);
   getline(cin, s.artist);
   getline(cin, s.minutes);
   getline(cin, s.seconds);
   getline(cin, s.album);
   songs.push_back(s);
}

int main() {
   vector<Song> songs;
   add_song_from_stdin(songs);
   Song &song = songs[0];
   cout << "song[0]:" << endl;
   cout << " \"" << song.title << "\"" << endl;
   cout << " \"" << song.artist << "\"" << endl;
   cout << " \"" << song.minutes << "\"" << endl;
   cout << " \"" << song.seconds << "\"" << endl;
   cout << " \"" << song.album << "\"" << endl;
}