问题描述
在C ++和C中,有多种方法可以将字符串转换为整数,但是我还没有找到一种转换方法无法解析浮点数.
In C++ and C there are multiple methods to convert a string to integer, but I haven't found a conversion method that fails on parsing a floating point number.
const float fnum = std::stof("1.5");
std::cout << fnum << std::endl; // prints "1.5", all okay
const int inum = std::stoi("1.5");
std::cout << inum << std::endl; // prints "1", but wrong!
我需要它来分析CSV文件的列类型.如果一列中的所有字段都是整数,则将该列存储为std :: vector<int>,如果为float,则为std :: vector<float>,否则将其存储为字符串.
I need this to analyse a CSV file for column type. If all fields from one column are integers, then store the column as std::vector< int>, if float, then std::vector< float>, else store it as strings.
唯一有希望的方法是:
std::string num = "1.5";
char *end = nullptr;
const long lnum = strtol(num.data(), &end, 10);
if (end != &*num.end()) {
std::cout << "Float? " << l << " / " << num << std::endl;
} else {
std::cout << "Integer! " << l << " / " << num << std::endl;
}
这有效,但是非常难看.有解决这个问题的C ++方法吗?
This works, but is quite ugly. Is there a C++-way to solve this?
推荐答案
您可以使用boost lexical_cast.如果强制转换失败,它将引发异常
You could use boost lexical_cast. It throws an exception if the cast fails
try
{
number = boost::lexical_cast<int>(your_string);
}
catch (const boost::bad_lexical_cast& exec)
{
// do something on fail
}
这篇关于从std :: string解析整数,但是如果float则失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!