cin. cin.getline() behavior.

Hi all,
I was going through some code in C++ and I came across an unexpected behavior.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main(){
    const int ArSize = 20;
    char name[ArSize];
    char dessert[ArSize];

    cout << "Enter the name: ";
    cin >> name;
    cout << "Enter the dessert: ";
    cin.getline(dessert, ArSize);
    cout << endl << endl;
    cout << name << dessert;
}

The above code gives the following output

Enter the name: Himansh                            
Enter the dessert:

Himansh





As you can see, the above code doesn't even gives us a chance to input the name of dessert. As per my knowledge, when we type "Himansh" and press enter, the above cin puts a newline character in input buffer, and when the program comes across cin.getline(), it passes newline character to it, and cin.getline() replaces this newline character to null character and discards the newline character.


Now, try replacing
 
cin.getline(dessert, ArSize);


to

 
cin >> dessert;


Now, this code works perfectly.
Now according to my knowledge , this process should go like this.
User types "Himansh" , press enter, the cin puts newline character in input buffer.
Now when cin comes across this newline character, AFAIK, the cin should terminate once it encounters newline. So why is it still accepting user input???

Thanks for reading this long description of my doubt.
Waiting for your reply.........
-Himansh
Last edited on

User types "Himansh" and presses enter so the input buffer contains

H i m a n s h \n

cin then reads H i m a n s h and stops at \n leaving \n in the input buffer.

getline will see that the input buffer is not empty and read everything up to \n and discard the \n. getline thus returns an empty string.

If you use cin instead of getline, cin will ignore any leading whitespace so will discard the \n and since the input buffer is now empty, cin will wait for user input.
cin >> dessert;
This will first ignore any leading whitespace, including space, tab or newline.
After that it will accept the next word into the variable dessert.
yes, my idea came to be correct.

Thank you all.
-Himansh
Topic archived. No new replies allowed.