可能的选项如下所述:
1. sscanf()
#include <cstdio>
#include <string>
int i;
float f;
double d;
std::string str;
// string -> integer
if(sscanf(str.c_str(), "%d", &i) != 1)
// error management
// string -> float
if(sscanf(str.c_str(), "%f", &f) != 1)
// error management
// string -> double
if(sscanf(str.c_str(), "%lf", &d) != 1)
// error management
这是一个错误(cppcheck 也显示),因为“在某些版本的 libc 上,没有字段宽度限制的 scanf 可能会因大量输入数据而崩溃”(请参阅 here 和 here) .
2. std::sto()*
#include <iostream>
#include <string>
int i;
float f;
double d;
std::string str;
try {
// string -> integer
int i = std::stoi(str);
// string -> float
float f = std::stof(str);
// string -> double
double d = std::stod(str);
} catch (...) {
// error management
}
此解决方案简短而优雅,但仅适用于兼容 C++11 的编译器。
3.流
#include <string>
#include <sstream>
int i;
float f;
double d;
std::string str;
// string -> integer
std::istringstream ( str ) >> i;
// string -> float
std::istringstream ( str ) >> f;
// string -> double
std::istringstream ( str ) >> d;
// error management ??
但是,使用此解决方案很难区分错误输入(请参阅here)。
4. Boost 的 lexical_cast
#include <boost/lexical_cast.hpp>
#include <string>
std::string str;
try {
int i = boost::lexical_cast<int>( str.c_str());
float f = boost::lexical_cast<int>( str.c_str());
double d = boost::lexical_cast<int>( str.c_str());
} catch( boost::bad_lexical_cast const& ) {
// Error management
}
但是,这只是sstream 的包装,文档建议使用sstream 来更好地管理错误(请参阅here)。
5. strto()*
由于错误管理,这个解决方案很长,这里有描述。由于没有函数返回纯 int,因此在整数的情况下需要进行转换(请参阅 here 了解如何实现此转换)。
6. Qt
#include <QString>
#include <string>
bool ok;
std::string;
int i = QString::fromStdString(str).toInt(&ok);
if (!ok)
// Error management
float f = QString::fromStdString(str).toFloat(&ok);
if (!ok)
// Error management
double d = QString::fromStdString(str).toDouble(&ok);
if (!ok)
// Error management
结论
总结起来,最好的解决方案是 C++11 std::stoi(),或者,作为第二种选择,使用 Qt 库。不鼓励使用所有其他解决方案或存在错误。