简体   繁体   中英

C++ cin.get() structs

So here is the rundown: I am creating a small music library using structs. The library has a few functions that it has to do with one of them being that I should be able to add new songs to the library. I have to use cin.get() and go from there but everytime I execute it, it goes into and infinite loop. Here is what my code for the add song functions looks like. The integer i is just some index value.

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

Any help helps.

I'd probably do something like this instead of using cin.get(), C strings, and static arrays:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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