gpt4 book ai didi

c++ - 如何在 C++ 中读取字符串中以空格分隔的多个 double ?

转载 作者:太空狗 更新时间:2023-10-29 21:19:35 50 4
gpt4 key购买 nike

我需要读入一个字符串,例如:

string str = "3 - 90.2 85.54 93.0";

...以这种格式。第一个数字显示 double 的数量,后跟“=”,然后是用空格分隔的 double 数量)。我知道如何将第一个数字读取为 int 以查找 double 数。然而,困扰我的是 double 的阅读。我尝试使用 stod 函数。

string str = "90.2 85.54 93.0";
size_t sz;

double x = stod(str,&sz);
double y = stod(str.substr(sz));
double z = stod(str.substr(sz));

但是,这最多只能读取 2 个 double ,因为 str.substr(sz) 将读取到字符串的末尾,并且 double 可以有不同的小数(可能是 89.54 或 89 或 89.6),所以我不能使用 substr 因为这需要我知道从起始索引中读取多少个字符。

有什么方法可以读取这些未知数量的 double 和未知数量的十进制数字吗?是否有另一种方法,例如 substr 来读取特定的索引或字符?我只是希望它们能够通过运行来阅读。稍后我可以将它存储到双数组中(我知道该怎么做)。

最佳答案

你可以使用字符串流

string str = "3 - 90.2 85.54 93.0";
stringstream ss(str);
int num; ss >> num; //read 3
char c; ss >> c; // read "-"
double d1; ss >> d1; // read 1
double d2; ss >> d2; // read 2
double d2; ss >> d2; // read 3

关于c++ - 如何在 C++ 中读取字符串中以空格分隔的多个 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26813600/

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