dommynik dommynik - 3 months ago 7
C++ Question

Parse integer from std::string, but fail if float

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!


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.

The only method that looks promising is this:

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;
}


This works, but is quite ugly. Is there a C++-way to solve this?

m.p m.p
Answer

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
}