Discussion on several input modes of C++ from keyboard

  • 2020-06-07 04:58:19
  • OfStack

As we all know, C++ can read input from the keyboard, and there are many ways to read input. Here are some common ways to read input

And the difference between them

1, cin

With cin input, the program treats the input as a series of 1 bytes. Each byte is interpreted as a character encoding. Whatever the data type, the input 1 starts with character data, and then the cin object is responsible for converting the data to other types

For example,


string name;
std::cin>>name;
std::cout<<name;

When you type in Michael Jackon and run the program you'll see that name only has Michael stored. Why is that?

cin USES whitespace (Spaces, tabs, and newlines) to determine the end of the string

When reading the character array, cin will read only the first word, and cin puts the string into the array and automatically adds null characters

The space between Michael Jackon is treated as an end character, while Jackon remains in the input queue until the next read of the input

How to solve this problem? Read on

2. getline ()

The getline () function reads the entire line and USES the enter key to determine the end of the input

Suppose you still want to read MIchael Jackon


String name ; 
getline(cin,name);
std::cout<<name:

Or you can use the char array


char name[50];
std::cin.getline(name,50);
std::cout<<name;

This is what you're going to see reading Michael Jackon

Although getline reads the end by reading the newline character, it does not hold the newline character. When it holds the string, it replaces the newline character with a null character

When getline finishes reading a line, it starts reading the next line, meaning we can skip a line

If we read a text file without reading a certain line, we can do so


string str;
getline(cin,str);

This will skip the first line

3. get ()

One variant of Istream, called get (), works in a similar way to getline (). They take the same arguments, interpret them the same way, and all read to the end of the line. Instead of discarding the newline character when it is read to the end of a line, it is left in the input queue


cin.get(name,50);
cin.get(dessert,50);

Suppose that a string is read, and when it is read again, the newline character is read. get () is considered to have reached the end of the line and is not read

How do you solve it?

We can add 1 cin. get() between reads; Used to read the next character, even if it is a newline character.


cin.get(name,50);
cin.get();
cin.get(dessert,50)

Related articles: