mardi 30 août 2016

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?

Aucun commentaire:

Enregistrer un commentaire