Using getline() in C++
Solution 1:
If you're using getline()
after cin >> something
, you need to flush the newline character out of the buffer in between. You can do it by using cin.ignore()
.
It would be something like this:
string messageVar;
cout << "Type your message: ";
cin.ignore();
getline(cin, messageVar);
This happens because the >>
operator leaves a newline \n
character in the input buffer. This may become a problem when you do unformatted input, like getline()
, which reads input until a newline character is found. This happening, it will stop reading immediately, because of that \n
that was left hanging there in your previous operation.
Solution 2:
If you only have a single newline in the input, just doing
std::cin.ignore();
will work fine. It reads and discards the next character from the input.
But if you have anything else still in the input, besides the newline (for example, you read one word but the user entered two words), then you have to do
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
See e.g. this reference of the ignore
function.
To be even more safe, do the second alternative above in a loop until gcount
returns zero.
Solution 3:
I had similar problems. The one downside is that with cin.ignore()
, you have to press enter 1 more time, which messes with the program.
Solution 4:
int main(){
.... example with file
//input is a file
if(input.is_open()){
cin.ignore(1,'\n'); //it ignores everything after new line
cin.getline(buffer,255); // save it in buffer
input<<buffer; //save it in input(it's a file)
input.close();
}
}