1. Enter a space character.
In the following code, you need to press the Enter key twice to display it. Because Getline has three parameters, the third parameter is the string Terminator, that is, when Getline encounters this Terminator, it does not accept input, for example, writing it as Getline (CIN, St, 's'); even if the input is abcsabc, only ABC is displayed.
Therefore, in the case above, some people say that Getline uses the carriage return ('/N') as the terminator by default. The first press enter to end the string, and the second press enter to start output.
#include<iostream> #include<string> using namespace std; int main(){ string s; getline(cin,s); cout<<s; return 0; }
(This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/lengyuhong/archive/2009/10/12/4659724.aspx)
However, there is a problem here, that is, if you need to call Getline (CIN, S) consecutively, if you do not do any processing, the input at the beginning of each time is the last Terminator, that is, enter, as a result, the second call is directly terminated (Getline does not ignore the linefeed at the beginning of the line, as long as Getline () encounters a linefeed, even if it is the first character, Getline will also stop reading the character and return it. The solution is as follows:
2. Use cin. Clear () or CIN. Ignore () to skip the initial Terminator.
For example
# Include <iostream> # include <string> using namespace STD; int main () {char STR [8]; cin. getline (STR, 5); cout <STR <Endl; cin. clear (); // if there is no clear, the following input is ignored because the CIN mark is not cleared. getline (STR, 5); cout <STR <Endl; System ("pause"); Return 0 ;}
You can also use cin. Ignore (1) to ignore a character;
Or cin. Ignore (1024, '/N.