如何在c ++中将字符串转换为double?
我有一个带数字的字符串向量,我想把它复制到double类型的矢量
while (cin >> sample_string)
{
vector_string.push_back(sample_string);
}
for(int i = 0; i <= vector_string.size(); i++)
{
if(i != 0 && i != 2 && i != vector_string.size()-1)
vector_double.push_back((double)vector_string[i]);
}
编辑:我无法使用BOOST
答案 0 :(得分:5)
我认为你应该使用STL提供的stringstream类。它使您能够从字符串转换为双倍,反之亦然。这样的事情应该有效:
#include <sstream>
string val = "156.99";
stringstream s;
double d = 0;
s << val;
s >> d;
答案 1 :(得分:2)
假设您已安装boost,
{
using boost::lexical_cast;
vector_double.push_back(lexical_cast<double>(vector_string[i]));
}
假设您没有安装boost,请添加此功能模板,然后调用它:
template <class T1, class T2>
T1 lexical_cast(const T2& t2)
{
std::stringstream s;
s << t2;
T1 t1;
if(s >> t1 && s.eof()) {
// it worked, return result
return t1;
} else {
// It failed, do something else:
// maybe throw an exception:
throw std::runtime_error("bad conversion");
// maybe return zero:
return T1();
// maybe do something drastic:
exit(1);
}
}
int main() {
double d = lexical_cast<double>("1.234");
}
答案 2 :(得分:0)
Boost(以及其他)提供了lexical_cast
,完全符合您的目的。