To take sentence as a input in c++

20,644

Solution 1

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.

Solution 2

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

Solution 3

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--){...}
Share:
20,644
sac
Author by

sac

Programmer knows C,C++ and C#

Updated on July 09, 2022

Comments

  • sac
    sac almost 2 years

    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
    
  • Arun A S
    Arun A S about 9 years
    Just curious , won't a single getchar() be enough? ( please correct me if I am wrong )
  • herohuyongtao
    herohuyongtao about 9 years
    @ArunA.S Yes, actually getchar() is neater and better. Updated the answer. Thanks. :P