0

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
alienflow
  • 400
  • 7
  • 19
  • Can't reproduce https://ideone.com/CH8wLu . As I asked in your [previous question](https://stackoverflow.com/q/49495294/4944425), are you sure that the original string doesn't contain any space? – Bob__ Mar 27 '18 at 09:30
  • @Bob__ sure 100%, my input is "5x^9" exactly, without spaces at all – alienflow Mar 27 '18 at 09:34
  • @Bob__ but i see that it works for you! So whats wrong ?? – alienflow Mar 27 '18 at 09:36
  • This seems related: https://stackoverflow.com/questions/19725070/discrepancy-between-istreams-operator-double-val-between-libc-and-libstd . [Here](https://wandbox.org/permlink/omUqCQqgxIWDkHzx) I could reproduce your issue, while [here](https://wandbox.org/permlink/0ZdBmArklMW9Hoco), changing the `x` with `z`, it could be parsed. – Bob__ Mar 27 '18 at 13:31

1 Answers1

0

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';
    }    
}
Bob__
  • 12,361
  • 3
  • 28
  • 42