cin.getline() is skipping an input in C++ [duplicate]
Solution 1:
This:
cin>>n;
Is reading the number only.
It leaves the trailing '\n'
on the stream.
So your first call to getline()
is reading an empty line containing just a '\n'
It is best not to mix the use of operator>>
and std::getline()
. You have to be very careful on whether you have left the newline on the stream. I find it easiest to always read a line at a time from a user. Then parse the line separately.
std::string numnber;
std::getline(std::cin, number);
int n;
std::stringstream numberline(number);
numberline >> n;
Solution 2:
your cin.ignore()
is in the wrong place. getline does not leave the trailing \n
newline character, it's the >>
symbol which does that.
What you probably want is
cin>>n;
cin.ignore();
Solution 3:
actually the cin buffer has \n remaining from last cin, so getline take this \n character and gets terminated; ignore the content of buffer before getline...
cin.ignore();
getling(cin, string_name);
//it will work smoothly