繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM