In c++, I want to input a string after I input a number.
This is my code.
Why string s doesn’t get any input?
What is the correct way of doing it?
Correct way-
#include <iostream>
#include<string>
using namespace std;
int main()
{
int b;
string s;
cin>>b;
cin>>s;
cout<<b<<endl;
cout<<s;
return 0;
}
I suspect that whatever you are using to get the string input, is getting the null character/end line character and assigning it to string. Its pretty common error programmers do.
EDIT 1 - getline usually reads the entire line, including the new line character etc. So it accepts new line character as a valid input, which most other inputs methods/keywords (idk what to call them atm XD) usually don’t.
PS, I think you can find something good here-
The problem is that you are not flushing the newline (’\n’) character after cin>> statement.
so you must need to flush the newline character out of the buffer in between. You can do it by using cin.ignore(). This happens because the >> operator leaves a newline \n character in the input buffer which which be taken by getline() prior to reading your next input.
Click here to see my code.
Why doesn’t this happen when we try to input 2 int which are on different lines?
This works but the previous one doesn’t.
Even if I try it this way I only get the first word of the string as input.
Oh, so you want to input a sentence? It wont work for that. Try Bansal’s method for that. I saw no indication for sentence (strings with white spaces have different input that strings without white spaces)
using cin.ignore() is the way to go bud, cause cin>>s will stop at the first whitespace it encounters
-
First of all you have to understand
how both cin>> and getline() works.cin>> starts working by first
eliminating all white spaces and
newline character. That’s why input
like in one line45 98 65
will be taken as 3 input. Why?, because cin>> will
automatically terminate and stop
taking input after getting any white
space or newline character. -
getline works differently. It takes
any character at starting whether it
is white space or newline. That’s why
i had to include cin.ignore() to
eliminate newline character. Another
property of getline is it will only
terminate after getting newline(’\n’)
character.
Exactly what I had to say!! Well explained!
Nice Explanation. Thanks.