如何在 char[] 中获取两个以空格分隔的整数?
我将得到一串看起来像这样的数字。
12 45
用空格分隔的两个整数。
输出将是 57。
我尝试过使用,
string numbersstream;
cin >> numbersstream;
istringstram twonumbers (numbersstream);
twonumbers >> a >> b;
但每次运行它时,只有 a 是正确的,b 不是。
还有哪些其他功能可以帮助我?或者这只是我的编码问题?
我在答案中已经得到了两种建议。
getline(cin,numbersstream);
感谢
cin << a << b;
大家抽出宝贵的时间。额外的方法将非常感激。
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;
istringstram 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题出在 cin 的输入上。使用
operator>>
以空格分隔。因此,如果用户输入“12 45”,则只会提取 12。您可以使用 getline 代替: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:试试这个:
问题是在您的代码中:
仅将一个空格分隔的单词(即 12)读取到字符串
numbersstream
中。因此,当您构建twonumbers
时,它实际上只有一个数字。因此它只设置“a”,而“b”未定义。您可以按照自己的方式进行操作,但这里真正需要的是将整行读入字符串中:
Try this:
The problem is that in your code:
Only reads one space separated word (ie 12) into the string
numbersstream
. Thus when you buildtwonumbers
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:
您只会读取第一个空白字符,
以下内容会将所有内容读入字符串,直到读取分隔符('\n')或文件结尾。分隔符被丢弃。
You are only reading until the first whitespace character with
The following will read everything into the string until a delimiter character is read ('\n') or end-of-file. The delimiter is discarded.