0

I found that std::endl means moving the cursor to new line and then flushing the cin buffer. but in this code , after using endl,getline doesn't work

#include <iostream>
#include <string>
using namespace std;
int main()
{
        string a,b;
        cout<<"The first string is: ";
        cin>>a;
        cout<<"The second string is: "<<endl;
        getline(cin,b); 
        cout<<"The second string you typed is: \n";
        cout<<b;
}
Long Trương
  • 13
  • 1
  • 2

1 Answers1

0

The thing with this code is that when you press enter for the first string, the enter press remains in the buffer and then when it comes to getline() command, it automatically takes that enter as the only input and moves forward. I am not very strong with this concept but I removed the endl from the code and it was still not taking input in 'b'. I just added 'cin.ignore()' before the getine() and that way it ignores whatever is in the buffer of inputs, which in this case is most likely enter key. I also find it good to use cin.ignore() whenever I use getline() as it will get rid of any unexpected results.

Dharman
  • 30,962
  • 25
  • 85
  • 135