我正在尝试转换std::string
为float/double
。我试过了:
std::string num = "0.6";
double temp = (double)atof(num.c_str());
但是它总是返回零。还有其他方法吗?
我正在尝试转换std::string
为float/double
。我试过了:
std::string num = "0.6";
double temp = (double)atof(num.c_str());
但是它总是返回零。还有其他方法吗?
Answers:
std::string num = "0.6";
double temp = ::atof(num.c_str());
对我而言,将字符串转换为双精度字是一种有效的C ++语法。
您可以使用stringstream或boost :: lexical_cast来完成此操作,但这些操作会降低性能。
啊哈,你有一个Qt项目...
QString winOpacity("0.6");
double temp = winOpacity.toDouble();
附加说明:
如果输入数据为const char*
,QByteArray::toDouble
则会更快。
标准库(C ++ 11)通过以下功能提供所需的功能std::stod
:
std::string s = "0.6"
std::wstring ws = "0.7"
double d = std::stod(s);
double dw = std::stod(ws);
通常,对于大多数其他基本类型,请参见<string>
。C字符串也有一些新功能。看到<stdlib.h>
ostringstream
本身太长了,无法输入,更不用说了..
词法转换非常好。
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
using std::endl;
using std::cout;
using std::string;
using boost::lexical_cast;
int main() {
string str = "0.6";
double dub = lexical_cast<double>(str);
cout << dub << endl;
}
try { ... boost::lexical_cast ... } catch (std::exception const& err) { //handle excpetion }
catch ( boost::bad_lexical_cast const& err )
捕获异常。
您可以使用std :: stringstream:
#include <sstream>
#include <string>
template<typename T>
T StringToNumber(const std::string& numberAsString)
{
T valor;
std::stringstream stream(numberAsString);
stream >> valor;
if (stream.fail()) {
std::runtime_error e(numberAsString);
throw e;
}
return valor;
}
用法:
double number= StringToNumber<double>("0.6");
如果您不想拖动所有增强,请使用strtod(3)
from- <cstdlib>
它已经返回了两倍。
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
int main() {
std::string num = "0.6";
double temp = ::strtod(num.c_str(), 0);
cout << num << " " << temp << endl;
return 0;
}
输出:
$ g++ -o s s.cc
$ ./s
0.6 0.6
$
为什么atof()不起作用...您在使用什么平台/编译器?
无论如何,您都不希望Boost lexical_cast用于字符串<->浮点。该用例子集是唯一一组始终如一地比旧功能更强大的提升-并且它们基本上集中了所有失败,因为它们自己的性能结果显示,与使用sscanf和printf进行这种转换相比,其性能降低了20-25倍。
自己搜索它。boost :: lexical_cast可以处理大约50次转换,并且如果排除那些涉及浮点数的转换,其效果与显而易见的替代品一样好(或更高)(具有为所有这些操作使用单个API的额外优势)。但是要带上浮标,就像泰坦尼克号一样,在性能方面会碰上冰山。
旧的专用str-> double函数都可以在30毫秒(或更短的时间)内完成10000个解析。lexical_cast大约需要650毫秒才能完成相同的工作。
我的问题:
我的解决方案(使用Windows函数_wcstod_l):
// string to convert. Note: decimal seperator is ',' here
std::wstring str = L"1,101";
// Use this for error detection
wchar_t* stopString;
// Create a locale for "C". Thus a '.' is expected as decimal separator
double dbl = _wcstod_l(str.c_str(), &stopString, _create_locale(LC_ALL, "C"));
if (wcslen(stopString) != 0)
{
// ... error handling ... we'll run into this because of the separator
}
HTH ...花了我很长时间才获得此解决方案。而且我仍然觉得我对字符串本地化和东西还不够了解...