如何从字符串中解析double?
我有以下代码,但它只能将字符串转换为double。如果字符串包含一个字母,它会导致错误如何从字符串中解析double?
while (cin >> s){
const char *c_ptr=s.c_str();
d = atof(c_ptr);
v.push_back(d);
}
我想输入类似“A1.2 3 4B”,并已在载体填充“1.2 3 4”
这个什么字符串:
1) replace all chars in the string that aren't digits or decimal points by spaces
2) read doubles in a loop
,因为你得到了解析双打摆脱之前的字母,就应该不再会导致的问题。
听起来是一个好主意。你如何使用替换函数来替换这些字符?我不能让str.replace()在C++ – code511788465541441
上工作。你可能会想在步骤2中使用istringstream,因为上面的代码只会从每个字符串中获得一个double。以http://www.daniweb.com/software-development/cpp/threads/54367为例。 –
我能想到的最简单的方法就是在for循环中自己完成替换。一个类似的例子可以在这里看到http://www.daniweb.com/software-development/cpp/threads/349806 –
http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/ –
只有当您知道您提前阅读了多少双打以及该字符串具有非数字字符时,sscanf才会有效。 –
如果输入是“4a1.2”,该怎么办?矢量中应该包含多少个数字?如果只有一个,它的价值应该是什么? –