【问题标题】:std::stringstream strange behaviourstd::stringstream 奇怪的行为
【发布时间】:2009-03-12 01:58:55
【问题描述】:

一些背景信息,对于家庭作业,我必须使用二叉树编写一个波兰符号计算器,为此我必须解析命令行输入,以便它能够正确构建二叉树,然后遍历它以给出输入的数学表达式的有效答案。

对于解析,我使用了 std::stringstream,这样我就可以轻松地将收到的 std::string 转换为有效的浮点数(或整数、双精度数)。我遇到的问题是以下代码,其中显示了错误以及我如何解决该问题。我希望有人能够告诉我我是否做错了什么并且 .clear() 不正确,或者这是标准库中处理此特定输入的方式中的错误(仅发生在 +和-)。

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string mystring("+");
    int num;
    char op;

    std::stringstream iss(mystring);
    iss >> num;

    // Seems it is not a number 
    if (iss.fail()) {
            // This part does not work as you would expect it to

            // We clear the error state of the stringstream
            iss.clear();
            std::cout << "iss fail bit: " << iss.fail() << std::endl;
            iss.get(op);
            std::cout << "op is: " << op << " iss is: " << iss.str() << std::endl;
            std::cout << "iss fail bit: " << iss.fail() << std::endl;

            // This however works as you would expect it to
            std::stringstream oss(iss.str());
            std::cout << "oss fail bit: " << oss.fail() << std::endl;
            oss.get(op);
            std::cout << "op is: " << op << " oss is: " << oss.str() << std::endl;
            std::cout << "oss fail bit: " << oss.fail() << std::endl;

    } else {
            // We got a number
    }   
}

程序的示例输出:

iss fail bit: 0
op is:  iss is: +
iss fail bit: 1
oss fail bit: 0
op is: + oss is: +
oss fail bit: 0

也许你们会看到我错过的一些东西,或者如果这确实是我的程序之外的一个错误,在这种情况下,我们将不胜感激在哪里报告这个问题的指针。

【问题讨论】:

    标签: c++ stl string libstdc++


    【解决方案1】:

    当你说:

      iss.clear();
      std::cout << "iss fail bit: " << iss.fail() << std::endl;
      iss.get(op);
    

    您正在尝试阅读已经阅读过的内容。您需要重置流读取指针:

      iss.clear();
      iss.seekg(0);    // start again
      std::cout << "iss fail bit: " << iss.fail() << std::endl;
      iss.get(op);
    

    【讨论】:

    • 但是,此时尚未读取 +,因为它从未从流中提取,因为它不是有效数字。为什么读指针失败时会前移?
    • 恐怕这就是流 i/o 的魔力。您必须按原样处理事情,而不是按您希望的那样处理。
    • X-Istence 我认为它是被提取的,因为“+”是正数的有效部分。比如“+10”。无论如何不应该是 "seekg" (seek get) 而不是 "seekp" (seek put) 吗?
    • 你是对的 - 我在我编写的代码中使用了 seekg() 来测试它。我不知道 seekp() 是怎么进去的!
    猜你喜欢
    • 2012-12-10
    • 2011-03-06
    • 2020-06-11
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多