【问题标题】:convert a string to chars and ints (a combination) with istringstream使用 istringstream 将字符串转换为字符和整数(组合)
【发布时间】:2025-11-25 15:10:02
【问题描述】:

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

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

【问题讨论】:

  • 无法复制 ideone.com/CH8wLu 。正如我在您的previous question 中所问的,您确定原始字符串不包含任何空格吗?
  • @Bob__ 肯定 100%,我的输入是“5x^9”,完全没有空格
  • @Bob__ 但我发现它对你有用!那怎么了??
  • 这似乎相关:*.com/questions/19725070/…Here 我可以重现您的问题,而 herex 更改为 z,它可以被解析。

标签: c++ string stream istringstream sstream


【解决方案1】:

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

参见例如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';
    }    
}

【讨论】:

  • 实际上,当我明确声明 x = 'x' 时,它成功了!