Tal
Tal

Reputation:

Reading some integers then a line of text in C++

I'm reading input in a C++ program. First some integers, then a string. When I try reading the string with getline(cin,stringname);, it doesn't read the line that the user types: instead, I get an empty line, from when the user pressed Enter after typing the integers.

cin>>track.day; //Int
cin>>track.seriesday; //Int
getline(cin,track.comment); //String

How can I clear the cin (cin.clear() doesn't work) so that the string won't fill itself with the "enter" key?

It's a normal input receiving, nothing special at the top of the code, I had a problem like this but I forgot the solution I need to clear the cin someway so the string won't get filled with "enter" key.

Upvotes: 2

Views: 467

Answers (1)

Evan Teran
Evan Teran

Reputation: 90422

I think that your cin of the ints is not reading the new line before the sentence. cin skips leading whitespace and stops reading a number when it encounters a non-digit, including whitespace.

So:

std::cin >> num1;
std::cin >> num2;
std::cin.ignore(INT_MAX, '\n'); // ignore the new line which follows num2
std::getline(std::cin, sentence);

might work for you

Upvotes: 3

Related Questions