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

时间:2018-03-27 09:14:48

标签: c++ string stream istringstream sstream

我认为有一些琐碎非常愚蠢的错误,但我无法指出它。有什么建议吗?

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

1 个答案:

答案 0 :(得分:0)

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

参见例如Discrepancy between istream's operator>> (double& val) between libc++ and libstdc++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';
    }    
}