Reading a list of string

what is the use of cin.get and cin.getline???

Hi @Ambuj-Singh-514796906079795,
here we first input n using cin>>n.
so after typing n, we generally press enter. so if we had directly used cin.getline(), it would have taken enter as one of the input.
So, in order to avoid that we use cin.get() before cin.getline().

->cin
It is used to read a word or character.
It terminates on encountering whitespace or endline charater (’\n’)

->cin.get(char_array,number_of_characters,delimiter)
To read characters including special characters like ’ ', ‘\n’ and ‘\t’.

->cin.getline(char_array,max_Size,delimiter)
It is used to read a sentence or a paragraph.
It terminates on encountering endline character.
It also reads the whitespace.

The get() function is much like getline() but rather than read and discard the newline character, get() leaves that character in the input queue.

get() leaves the delimiter in the queue thus letting you able to consider it as part of the next input.

Explanation:
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’

hopes dis helps

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.