0

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

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
4

1 回答 1

0

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

有关更多详细信息,请参见libc++ 和 libstdc++ 之间的 istream 运算符>> (double& val)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';
    }    
}
于 2018-03-27T14:14:15.373 回答