gpt4 book ai didi

c++ - 在 char 数组中使用 sstream 解析器整数

转载 作者:搜寻专家 更新时间:2023-10-31 01:26:32 26 4
gpt4 key购买 nike

在使用 sstream 解析 char 数组中的整数时,我已经被困了几个小时。我不知道为什么在while循环中多了一次迭代。

//main.cpp
#include <iostream>
#include <sstream>
int main()
{
char data[5] = "1 23";
//char data[4] = {'1', ' ', '2', '3'}; another attempt
std::stringstream stream;
stream << data;
int count = 1;
while (stream)
{
double x = 0;
stream >> x;
std::cout << count << " " << x << std::endl;
count++;
}
return 0;
}

程序输出显示:

1  1
2 23
3 0

我使用以下命令编译程序。

g++ main.cpp

我认为有 2 个整数,所以只有 2 次迭代。我不知道为什么 while 循环中有 3 次迭代。我想这是因为 char 数组末尾的 '\0',但我试过了,它得到了相同的结果。

有什么建议吗?谢谢。

最佳答案

您没有检查 stream >> x 是否成功:

if (stream >> x)
{
std::cout << count << " " << x << std::endl;
count++;
}

会完成这项工作。

您还可以将其包含在循环中:

double x = 0;
while (stream >> x)
{
std::cout << count << " " << x << std::endl;
count++;
}

关于c++ - 在 char 数组中使用 sstream 解析器整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55181972/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com