Search code examples
c++numbersstringstreamwords

Can I tell if a std::string represents a number using stringstream?


Apparently this is suposed to work in showing if a string is numerical, for example "12.5" == yes, "abc" == no. However I get a no reguardless of the input.

std::stringstream ss("2");
double d; ss >> d;
if(ss.good()) {std::cout<<"number"<<std::endl;}
else {std::cout<<"other"<<std::endl;}

Solution

  • You should use an istringstream so that it knows it's trying to parse input. Also, just check the result of the extraction directly rather than using good later.

    #include <sstream>
    #include <iostream>
    
    int main()
    {
        std::istringstream ss("2");
        double d = 0.0;
        if(ss >> d) {std::cout<<"number"<<std::endl;}
        else {std::cout<<"other"<<std::endl;}
    }