How to read string with whitespace in C++?

in the first scanf, I usually write it as scanf("%d\n", …) to trash the newline character, there’s no need for extra getchar and also safer just in case there’s some white space next to t :slight_smile:

1 Like

Your reply is awesome… It simply corrected my problem… actually my loop for test cases was taking it’s first string to be blank or something and accordingly performing wrong output. also didn’t give output for the last string entered. but after using your way it’s perfect!
Thanx mate…

perfect explaination for how to use getline.thanx

will not work for CodeChef: Practical coding for everyone

Thanks a lot for sharing this. I was stuck on it since hours finally found a precise explanation!
Have a nice day!

You can use getline() but BEWARE! not to use cin>> before that as it >> does not clear the buffer so getline() will consider the ‘\n’ (the enter key that you pressed after using cin>>) as the input string and will immediately be executed as an empty string.
So use getc(stdin) or getchar() before getline() to clear the buffer.

int n; string str;
cin>>n;
getchar(); //OR getc(stdin)
getline(cin,str);

7 Likes

Thanks a lot. Your ans is perfect and complete.

Thanks alot!

Thank you so much!

It not work if we take “12:20 AM” string

It not work if take “12:09 AM” String