difference between cin.get() and cin.getline()

cin.getline() reads input up to '\n' and stops

cin.get() reads input up to '\n' and keeps '\n' in the stream

For example :

char str1[100];
char str2[100];
cin.getline(str1 , 100);
cin.get(str2 , 100);
cout << str1 << " "<<str2;

input :
1 2
3 4
output 1 2 3 4 // the output expexted

When reverse them
For example :

char str1[100];
char str2[100];
cin.get(str2 , 100);
cin.getline(str1 , 100);
cout << str1 << " "<<str2;

input :
1 2
3 4
output 1 2 // the output unexpexted because cin.getline() read the '\n'


There are an equivalent number of advantages and drawbacks, and -essentially- all depends on what you are reading: get() leaves the delimiter in the queue thus letting you able to consider it as part of the next input. getline() discards it, so the next input will be just after it.

If you are talking about the newline character from a console input,it makes perfectly sense to discard it, but if we consider an input from a file, you can use as "delimiter" the beginning of the next field.

What is "good" or "safe" to do, depends on what you are doing.


get() extracts char by char from a stream and returns its value (casted to an integer) whereas getline() is used to get a line from a file line by line. Normally getline is used to filter out delimiters in applications where you have a flat file(with thousands of line) and want to extract the output(line by line) using certain delimiter and then do some operation on it.

Tags:

C++

Get

Cin

Getline