问题
I have a problem getting a string. I use
getline(cin,string);
but there is some kind of a bug and it skips a row when I press enter, is there a solution to this problem, or maybe another function to get a string with empty spaces?
回答1:
My guess is that you are doing cin >> someVar
somewhere before you do the getline()
.
cin >> someVar
Doesn't read a complete line, but stops on the first whitespace character, and the newline \n
remains unconsumed., which then causes the skipping of line in getline()
If this is the case,
To fix it, you need to add a cin.ignore()
statement before the getline()
to consume the \n
newline character (or any other extra characters) left in the input stream by the >>
stream extractor.
来源:https://stackoverflow.com/questions/6354975/getting-a-string-c