I\'m creating a simple console application in C++ that gets string and char inputs from the user. To make things simple, I would like to use the string and
You are using std::isstream::ignore()
before std::getline()
. std::cin.ignore()
will extract the first character from the input sequence and discard that.
http://www.cplusplus.com/reference/istream/istream/ignore/
cin>>var;
only grabs the var
from the buffer, it leaves the \n
in the buffer,
which is then immediately grabbed up by the getline
So, following is just fine, (if I understood correctly your problem)
cin>>var;
cin.ignore(); //Skip trailing '\n'
getline(cin, var);
As per your edited post
You don't have to use cin.ignore();
for geline
This extracts characters from buffer and stores them into firstName
or (lastName
) until the delimitation character here -newline ('\n'
).
ignore()
does not skip a line, it skips a character. Could you send example code and elaborate on the need for cin.ignore()
?
So basically, cin>>var
leaves the '\n' character out of its buffer. So now when you call
getline it reads the '\n' character and stops. Therefore we use cin.ignore() to ignore the first character getline reads i.e '\n' when we use it after cin.
But getline doesn't leave '\n' character instead it stores everything in its buffer till it find '\n' character, then stores '\n' character as well and then stops.
So in your code when you are using cin.ignore() after a getline and again uses getline to take input, it ignores the first character of the string instead of '\n'. That is why the first character is missing.
Hope this answers your question.
std::cin.ignore()
will ignore the first character of your input.
For your case, use std::cin.ignore()
after std::cin
and then getline()
to ignore newline character as:
cin>>ch;
cin.ignore(); //to skip the newline character in the buffer
getline(cin,var);