sac
sac

Reputation: 137

To take sentence as a input in c++

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

Upvotes: 3

Views: 24076

Answers (3)

herohuyongtao
herohuyongtao

Reputation: 50667

The reason is that cin>>t stops at the first non-numeric character, which is the newline. The next cin.getline(b,100000) will read this newline character into b and "run run" to c.

To avoid this, you can first read the newline character into somewhere else. Like

cin >> t;

// read the newline character
getchar();

while(t--){...}

Upvotes: 3

Vinay Shukla
Vinay Shukla

Reputation: 1844

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.

Upvotes: 4

senfen
senfen

Reputation: 907

Big arrays are not good idea. Try use std::string instead.

#include <iostream>
#include <string>

int main() {
    std::string lineOne;
    std::string lineTwo;

    std::getline(std::cin, lineOne);
    std::getline(std::cin, lineTwo);

    std::cout << lineOne << "\n" << lineTwo;
    return 0;
}

Upvotes: 3

Related Questions