cin of Instream
problems that occur when CIN is in use
CIN uses whitespace (spaces, tabs, and line breaks) to confirm the end of the string when it waits for user input.
For example: Enter a Alan Dreeb, then encounter a space, Alan is assigned to the first variable, Dreeb is assigned to the second variable.
int main ()
{
char name[20];
Char favorite[20];
cout << "Enter your name:\n";
CIN >> name;
cout >> "Enter your favorite:\n";
CIN >> favorite;
cout << "Name:" << name << Endl;
cout << "favorite:" << favorite;
}
Output:
Enter your name:
Alan Yao
Enter your favorite:
Name:alan
Favorite:yao
Just enter a name for you, because first of all, Alan Yao, when Cin reads the space and thinks it's over, add the following after Alan. When the program runs to CIN >> favorite, the program reads to Yao, and all the yao\0 are assigned to favorite. using Cin.getline ()
Cin.getline () is a line-oriented input that uses a newline character entered with the ENTER key to confirm the end. There are two parameters, the first is the variable to be processed, and the second is the number of characters to read (remember that there is a null character). It does not save line breaks, and the old library is not very friendly to support this function.
int main ()
{
char name[20];
Char favorite[20];
cout << "Enter your name:\n";
Cin.getline (name,20);
cout >> "Enter your favorite:\n";
Cin.getline (favorite,20);
cout << "Name:" << name << Endl;
cout << "favorite:" << favorite;
}
Output:
Enter your name:
Alan Yao
Enter your favorite: Sport
Name:alan Yao favorite: Sport
using Cin.get ()
To better support the old version of C + + and to see what the user is typing, it's easier to check for errors. Using Cin.get () can be clearer. It no longer reads and discards line breaks. The parameters are similar to Cin.getline ().
' Cin.getline (name,20) ==cin.get (name,20). Get () '