Strings 02 - Sorting

In the given lecture of the same title,Sir uses [cin.get(); ] statement after [cin>>n;]
I did not understand the use of cin.get when we have taken value of n using cin>>n and used a loop for strings intake after that

cin will automatically terminate when it get a space while cin.get can input spaces.
for example:
if you use cin to get a string “ambi singh”
ie. string s;
cin>>s;

s will only contain ambi.

while if you you cin.get(), then it will contain ambi as well as singh.

Thanks

I understand the use of cin.get() …But in the video we first create a variable n,input it using cin>>n and then have a loop to input the n strings using getline(cin,s[i]),Why is then this cin.get() between ??My ques is in context to the video

1 Like

Also,if I do not use cin.get() …The code ignores the last input string

I haven’t seen the video. please elaborate your doubt. you can show me the code also

Kindly refer to my code link attached.I have commented my doubt in it as well. https://ide.codingblocks.com/s/314880

hi @ambisingh10
cin leaves the ‘\n’ character in the input buffer
cin.getline() reads characters till ‘\n’ is encountered. If ‘\n’ is already present in the input buffer, that will be read and s[0] will not be able to take the input for the first string we actually intended. To verify this, you can remove the cin.get() line and then see what is actually being stored in the array.
So to avoid this thing, cin.get() has been added after cin, so that the extra “\n” lying in the input buffer is taken care of.
You can alternatively use the fflush(stdin) function to clear the input buffer and avoid such things.

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.