My program should create a simple list: name(string), rating(int), watched/unwatched(string).
I understand that using std::cin>> leaves an '\n' at the end so I have to use cin.ignore() but it seems it also fails the other way around somehow.
void write()
{
int rating;
string name, watch, wprint;
cout << "Modifying" << endl;
f_list.open ("TextFile.txt", ios::app);
cout << "Name/Title?" << endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
getline(cin, name);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Rating?" << endl;
if (!(cin >> rating));
{
cin.clear();
cout << "Error again" << endl;
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Watched or unwatched?" << endl;
getline(cin, watch);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (watch == "w" || watch == "yes" || watch == "y")
{
watch = "W";
wprint = "Watched";
}
else
{
watch = "DW";
wprint = "Didn't watch";
}
cout << name << " (" << rating << "/10) (" << wprint << ") has been added to the list" << endl;
f_list << name << " " << rating << " " << watch << endl;
}
First my cin >> rating was always zero, no matter what I did and it also returned errors and went in an infinite loop. Then I SOMEHOW fixed it but I dont know how and now my 2 getline()s need to be entered TWICE!
Could somebody explain why doesn't this work for me? And which parts of this code is unnecessary?
std::getlinedoesn't leave the\nin the buffer, formatted extraction does! You're clearing the input. - LogicStuffstd::istream::ignorebetween every extraction. - LogicStuff