如何在 char[] 中获取两个以空格分隔的整数?

发布于 2024-12-03 21:13:46 字数 498 浏览 0 评论 0原文

我将得到一串看起来像这样的数字。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

够钟 2024-12-10 21:13:46

问题出在 cin 的输入上。使用operator>>以空格分隔。因此,如果用户输入“12 45”,则只会提取 12。您可以使用 getline 代替:

getline(cin,numbersstream);

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);
谁的新欢旧爱 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);

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);
倾城泪 2024-12-10 21:13:46

您只会读取第一个空白字符,

cin >> numberstream;

以下内容会将所有内容读入字符串,直到读取分隔符('\n')或文件结尾。分隔符被丢弃。

getline(cin,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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文