c++ input of a string that contains spaces

can someone clear my doubts ? i m facing problems in the above mentioned code links!

Give forums a search.

This issue is because of the newline character after t.

The input of-


It can actually be written as-


Your getline is getting stuck on this newline character and this causes runtime error if you use this string anywhere. You need to either use cin.ignore, or use a dummy char/string variable to take this newline character, and then proceed onwards.

Also, give forums a search as this has been attended to previously as well, may answer any arising doubts.

Assuming you typed: 5"enter" John"enter". Then cin >> number reads JUST 5. leaving the new-line (enter) character on the stream. Thus when you try and read the name with getline(cin,name) it reads to the end of line. BUT NOTE there is a new-line character just there ready to be read (thus names will be empty (because you did not read off the new-line character after the 5). If you want to switch between >> and getline() you need to be carefull about trailing end of lines on your input.

->copied comment of Loki Astari

You can follow this thread on stack overflow… https://stackoverflow.com/questions/5739937/using-getlinecin-s-after-cin

using namespace std;
int main()
    int t;
    cin >> t;
    string a;
    cout << a;

Try to run this… It will output what you want, not correct way but just trying to explain that comment. Hope that stack overflow link would be helpful.

yes it helped brother , thankyou

bro i searched and its not possible to search so deep and back .
i had a problem , i posted it , so that someone could possibly help out.

 search so deep and back

:confused: .

Anyways, totally letting this go, I will just make it clear I didnt made any snipe related to it. I understand your PoV and thats why I answered it in no less detail. But, its a frequently asked Q, and its my duty to recommend a search hence.

int t;
cin >> t;

I tried using this code once, but got an error. Not sure why.!

The best way to input string in these cases when you want to omit a character and the input time or ignore some line terminator or the other literal is to use getchar() . using getchar() and taking input character by character can actually work as you can choose when to stop taking input . Take note that you have to handle newline characters that are left in the buffer during previous inputs as they may change the string you wanted to input .