我目前正在尝试获取一个字符串 ("0.1") 并在带有 gcc4.2 的 Xcode 10.6 中使用 C++ 将其转换为 double 。
我正在使用从 another question 中提取的函数,但是当我尝试使用该函数时,根据 gdb,我的输入是 (string)"0.1",但我的输出是 (double)2.1220023981051542e-314。
这是我直接复制的代码片段:
double strToDouble(std::string const &numberString)
{
istringstream inStream(numberString);
double doubleValue;
inStream >> doubleValue;
if(!(inStream && (inStream >> std::ws).eof()))
{
return 0.0;
}
return doubleValue;
};
我使用的是 C++ 而不是 Obj-C,因为它最终可能必须在 *nix 或 Windows 机器上编译。
我天生就是一名 PHP 程序员,但我需要加快一些数字运算的速度,所以我使用编译语言来完成。大学处理低级语言已经很长时间了=P。所以,如果有人有想法,我们将不胜感激......
Drew J. Sonne。
完整代码:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
/*
* @var delimiters the string to define a break by
* @var str the string to break
* @var tokens where to store the broken string parts.
*/
void explode(const string& delimiters, const string& str, vector<string>& tokens)
{
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
};
/*
* @var numberString double to be converted as a string.
*/
double strToDouble(std::string const &numberString)
{
istringstream inStream(numberString);
double doubleValue;
inStream >> doubleValue;
if(!(inStream && (inStream >> std::ws).eof()))
{
return 0.0;
}
return doubleValue;
};
class Cluster {
private:
vector<double> latStore;
vector<double> lngStore;
public:
Cluster(int,string,string);
};
/*
* @var latString a comma seperated list of doubles for the latitudes.
* @var lngString a comma separated list of doubles for the longitudes.
*/
Cluster::Cluster(int newLocationLength, string latString, string lngString)
{
// mark our vectors
vector<string> latStoreString;
vector<string> lngStoreString;
// Explode our input strings.
explode(",", latString, latStoreString);
explode(",", lngString, lngStoreString);
for( int i = 0; i < latStoreString.size(); i++)
{
// Grab the latitude and store it.
string tempLat = latStoreString[i];
double latDouble = strToDouble(tempLat);
latStore.push_back( strToDouble(tempLat) );
// Grab the longitude and store it.
string tempLng = lngStoreString[i];
lngStore.push_back( strToDouble(tempLng) );
}
}
int main (int argc, char * const argv[]) {
Cluster *rect = new Cluster("0.1,0.4","0.1,0.4");
return 0;
}
最佳答案
这可能是STL Debug模式引起的。在目标的预处理器宏build设置中删除 _GLIBCXX_DEBUG 宏。
关于c++ - 在 C++ 中使用 istringstream 进行字符串到双重转换的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1698265/