This simple code should take in a string and print the same…i am using getline(cin,s) as the string can contain spaces,but i dont know why,whenever I use getline(cin,s),an extra blank line is getting printed,but when I use cin,it works perfectly fine(although now the string cant have space)…why is this error happening.
I am attaching screenshots for the same.
1)PROOF OF EXTRA BLANK LINE-http://ctrlv.in/976495
2)AFTER REPLACING GETLINE WITH CIN-http://ctrlv.in/976496
getchar() before the while loop
The reason is you’ve used cin >> t before using getline. The " >> " operator leaves a newline ‘\n’ character in the input buffer. This may become a problem when you do unformatted input, like getline(), which reads input until a newline character is found. The getline now takes that ‘\n’ which was created by " >> " operator and it is considered as an input. So remember, whenever you use getline after cin, you must use getchar(). getchar() gets this ‘\n’ character.
Thanks…it worked…any idea why it was not working earlier?..
Trailing newline character after “5” is the most probable reason. It will then take string like “\nstring”. But again, i am not 100% sure for this case.
i would say better use cin.ignore() it will work the same