Search code examples
c++stringstreamistringstreamsstream

convert a string to chars and ints (a combination) with istringstream


I think that there's some trivial very silly bug, but i can't nail it. Any advice?

string stuff = "5x^9";
istringstream sss(stuff);
double coeff;
char x, sym;
int degree;

sss >> coeff >> x >> sym >> degree;
cout << "the coeff " << coeff << endl;
cout << "the x " << x << endl;
cout << "the ^ thingy " << sym << endl;
cout << "the exponent " << degree << endl;

The output:

the coeff 0
the x
the ^ thingy 
the exponent 1497139744

And it should be, i suppose

the coeff 5
the x x
the ^ thingy ^
the exponent 9

Solution

  • Your problem seems related to the presence of the x character after the number you want to extract from your string ("5x"), which causes parsing issues in some library implementations.

    See e.g. Discrepancy between istream's operator>> (double& val) between libc++ and libstdc++ or Characters extracted by istream >> double for more details.

    You can avoid this, either changing the name of the unknown (e.g. x -> z), or using a different extraction method, like this, for example:

    #include <iostream>
    #include <string>
    #include <sstream>
    #include <stdexcept>
    
    int main(void)
    {
        std::string stuff{"5x^9"};
    
        auto pos = std::string::npos;
        try {
            double coeff = std::stod(stuff, &pos);
            if ( pos == 0  or  pos + 1 > stuff.size() or stuff[pos] != 'x' or stuff[pos + 1] != '^' )
                throw std::runtime_error("Invalid string");
    
            int degree = std::stoi(stuff.substr(pos + 2), &pos);
            if ( pos == 0 )
                throw std::runtime_error("Invalid string");
    
            std::cout << "coeff: " << coeff << " exponent: " << degree << '\n';
        }
        catch (std::exception const& e)
        {
            std::cerr << e.what() << '\n';
        }    
    }