如何在 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)
谁的新欢旧爱2024-12-10 21:13:46
试试这个:
int main()
{
int a;
int b;
std::cin >> a >> b;
std::cout << a+b << "\n";
}
问题是在您的代码中:
cin >> numbersstream;
仅将一个空格分隔的单词(即 12)读取到字符串 numbersstream
中。因此,当您构建 twonumbers
时,它实际上只有一个数字。因此它只设置“a”,而“b”未定义。
您可以按照自己的方式进行操作,但这里真正需要的是将整行读入字符串中:
std::getline(std::cin, numbersstream);
istringstram twonumbers (numbersstream);
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
问题出在 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: