Cin. get and cin. getline

What is the difference between cin. get and cin. getline

@Tiwary725
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 expected

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

I couldn’t understand the line “and keeps \n in stream”
Please don’t use bookish language. could you please explain this line that you have written?

@Tiwary725 there comes a input queue(buffer) which stores all the inputs which should be read.
cin.get() keeps that ‘\n’ in that queue it do not discard it like cin.getline(), hence in the above second example we get only 1 2 as output because our cin.getline read ‘\n’ which was in input queue because of cin.get() and does not read 3 4.

I understood everything. Thank You Sir !!

1 Like