我正试图转换std::string
为float/double
.我试过了:
std::string num = "0.6";
double temp = (double)atof(num.c_str());
Run Code Online (Sandbox Code Playgroud)
但它总是返回零.还有其他方法吗?
Tim*_*imW 116
std::string num = "0.6";
double temp = ::atof(num.c_str());
Run Code Online (Sandbox Code Playgroud)
对我来说,将字符串转换为double是一种有效的C++语法.
您可以使用stringstream或boost :: lexical_cast来实现它,但这些会带来性能损失.
啊哈哈,你有一个Qt项目......
QString winOpacity("0.6");
double temp = winOpacity.toDouble();
Run Code Online (Sandbox Code Playgroud)
额外注意:
如果输入数据是a const char*
,QByteArray::toDouble
会更快.
Man*_*d3r 94
标准库(C++ 11)提供了所需的功能std::stod
:
std::string s = "0.6"
std::wstring ws = "0.7"
double d = std::stod(s);
double dw = std::stod(ws);
Run Code Online (Sandbox Code Playgroud)
我想标准库也在内部转换,但这种方式使代码更清晰.通常对于大多数其他基本类型,请参阅<string>
.C字符串也有一些新功能.看到<stdlib.h>
Bil*_*nch 29
词汇演员非常好.
#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;
}
Run Code Online (Sandbox Code Playgroud)
Edi*_*enz 14
你可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
用法:
double number= StringToNumber<double>("0.6");
Run Code Online (Sandbox Code Playgroud)
DaC*_*own 10
是的,有词汇演员.使用stringstream和<<运算符,或使用Boost,他们已经实现了它.
您自己的版本可能如下所示:
template<typename to, typename from>to lexical_cast(from const &x) {
std::stringstream os;
to ret;
os << x;
os >> ret;
return ret;
}
Run Code Online (Sandbox Code Playgroud)
你可以使用boost lexical cast:
#include <boost/lexical_cast.hpp>
string v("0.6");
double dd = boost::lexical_cast<double>(v);
cout << dd << endl;
Run Code Online (Sandbox Code Playgroud)
注意:boost :: lexical_cast抛出异常,所以你应该准备好在传递无效值时处理它,尝试传递字符串("xxx")
如果您不想拖动所有增强,请使用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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
$ g++ -o s s.cc
$ ./s
0.6 0.6
$
Run Code Online (Sandbox Code Playgroud)
为什么atof()不起作用...您在使用什么平台/编译器?