The difference between cin. Get of and cin. Getline of

  • 2020-04-02 01:40:16
  • OfStack

Cin. Getline () and cin. Get () are both line-oriented reads of input, that is, whole lines are read at once rather than a single number or character, but there are some differences.

Cin. Get () reads a full line at a time and leaves the newline generated by the Enter key in the input queue, for example:


#include <iostream>
using std::cin;
using std::cout;
const int SIZE = 15;
int main( ){
cout << "Enter your name:";
char name[SIZE];
cin.get(name,SIZE);
cout << "name:" << name;
cout << "nEnter your address:";
char address[SIZE];
cin.get(address,SIZE);
cout << "address:" << address;
}

Output:
Enter your name: jimmyi shi
Name: jimmyi shi
Enter your address: address:

In this example, cin-.get () reads the input name into the name and leaves the newline '/n' generated by Enter in the input queue (input buffer), so the next cin-.get () finds the '/n' in the buffer and reads it, resulting in the second unable to Enter and read the address. The solution is to call cin. Get () again after the first call to cin. Get () to read the '/n' character, can be composed as cin. Get (name,SIZE). .

Cin. Getline () reads a full line at a time and discards the newline generated by the Enter key, such as:


#include <iostream>
using std::cin;
using std::cout;
const int SIZE = 15;
int main( ){
cout << "Enter your name:";
char name[SIZE];
cin.getline(name,SIZE);
cout << "name:" << name;
cout << "/nEnter your address:";
char address[SIZE];
cin.get(address,SIZE);
cout << "address:" << address;
}

Output:
Enter your name: jimmyi shi
Name: jimmyi shi
Enter your address: YN QJ
Address: YN QJ

Because the newline generated by Enter is discarded, the next read of the address by cin. Get () is not affected.
If cin. Get () is read in one character at a time, but cin. Get () does not ignore any characters, the carriage returns need to be handled separately.

Two notes:
(1) learn to distinguish get() from getline();
(2) the newline symbol is \n, not /n;


Related articles: