得到一个双出字符串c++
get a double out a string c++
我正在寻找一种在c++中从字符串中获得双精度的有效方法。我现在使用cstring to double函数,但我不能使用它,因为这个字符串的格式如下:
DOUBLE - SPACE - REST OF STRING THAT I ALSO NEED TO SAVE.
问题是,double可以有不同的大小,那么我如何才能有效地获得double,并且我仍然能够保存字符串的其余部分。
std::istringstream s( theString );
s >> theDouble;
s
现在包含字符串的其余部分,可以很容易地提取。
使用istringstream
读取双值,忽略一个字符(需要空格),然后读取行的其余部分。
string s = "1.11 my string";
double d;
string rest;
istringstream iss(s);
iss >> d;
iss.ignore(); // ignore one character, space expected.
getline(iss, rest, ' ');
如果您的输入有固定的格式。你可以,先用空格分隔。然后你有以下内容:
DOUBLE
REST OF STRING THAT I ALSO NEED TO SAVE.
拆分:
std::string str = "3.66 somestring";
std::stringstream ss(str);
std::string buffer;
while(std::getline(ss, buffer, ' ')) {
// add necessary data to containers...
}
现在您可以使用std::atof
来解析您的替身。
edit:添加了拆分代码: