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
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