使用 istringstream 将字符串转换为字符和整数(组合)

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

我认为有一些微不足道的非常愚蠢的错误,但我无法解决。有什么建议吗?

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 coeff 0
the x
the ^ thingy 
the exponent 1497139744

我想应该是

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

您的问题似乎与要从字符串中提取的数字 ("5x") 后的 x 字符有关,这会导致某些库实现出现解析问题。

参见例如Discrepancy between istream's operator>> (double& val) between libc++ and libstdc++ or Characters extracted by istream >> double了解更多详情。

您可以避免这种情况,要么更改未知的名称(例如 x -> z),要么使用不同的提取方法,例如:

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