一些背景资料,对于家庭作业我不得不使用二叉树写一个波兰记号计算器,对于这个工作,我不得不解析命令行输入,所以它会正确地构建二叉树,然后去在它给一个有效的回答已输入的数学表达式。

有关解析我用一个std :: stringstream的,这样我就能够轻松地在的std :: string我被移交转换为有效的float(或整数,双)。我跑过的问题是下面的代码,其中有展示的错误,如何解决这个问题。我希望有人会在哪里能告诉我,如果我做错了什么和.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

也许你们会看到一些我错过了,或者,如果这确实是一个bug上涨超出了我的计划,在这种情况下指针在何处报告此将不胜感激。

有帮助吗?

解决方案

当你说:

  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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top