To take sentence as a input in c++

sac picture sac · Apr 3, 2015 · Viewed 18k times · Source

I am trying to take the input of the two sentences one after the other,but while printing it is printing a blank space and in the next line it is printing the first sentence and the loop is exiting.

Here is my code:

int main()
{

    char b[100000];
    char c[100000];
    int t;
    cin>>t;
    while(t--)
    {
        cin.getline(b,100000);
        cin.getline(c,100000);
        cout<<b<<"\n"<<c<<"\n";
    }
}

The input:

1
run run
good sentence

The output:

Blankspace
run run

Answer

Vinay Shukla picture Vinay Shukla · Apr 3, 2015
cin >>t;

This will prompt the user for some input. Assuming the user does what's expected of them, they will type some digits, and they will hit the enter key.

The digits will be stored in the input buffer, but so will a newline character, which was added by the fact that they hit the enter key.

cin will parse the digits to produce an integer, which it stores in the num variable. It stops at the newline character, which remains in the input buffer.

    cin.getline(b,100000);
    cin.getline(c,100000);

Later, you call cin.getline(b,100000);, which looks for a newline character in the input buffer. It finds one immediately, so it doesn't need to prompt the user for any more input. So it appears that the first call to getline didn't do anything, but actually it did.