How to get two integers separated by space in a char[]?
I will be getting a string of numbers that looks like this.
12 45
Two integers separated with space.
The output will be 57.
I have tried using,
string numbersstream;
cin >> numbersstream;
istring开发者_如何学运维stram twonumbers (numbersstream);
twonumbers >> a >> b;
But each time I run it, only a is correct, b isn't.
What other functions is there to help me? Or is this just a coding problem I have?
I got two kinds of suggestions already in the answers.
getline(cin,numbersstream);
And
cin << a << b;
Thank you all for your time. Additional methods will be very appreciated.
The problem is with your input from cin. Using operator>>
is whitespace delimited. So if the user types "12 45", only the 12 will be extracted. You could use getline instead:
getline(cin,numbersstream);
Try this:
int main()
{
int a;
int b;
std::cin >> a >> b;
std::cout << a+b << "\n";
}
The problem is that in your code:
cin >> numbersstream;
Only reads one space separated word (ie 12) into the string numbersstream
. Thus when you build twonumbers
it actually only has one number in it. Hence it only sets 'a' and 'b' is left undefined.
You could do it your way but what you really need here is to read the whole line into the string:
std::getline(std::cin, numbersstream);
istringstram twonumbers (numbersstream);
You are only reading until the first whitespace character with
cin >> numberstream;
The following will read everything into the string until a delimiter character is read ('\n') or end-of-file. The delimiter is discarded.
getline(cin,numbersstream);
精彩评论