簡體   English   中英

std :: stringstream奇怪的行為

[英]std::stringstream strange behaviour

一些背景信息,對於一項家庭作業,我不得不使用二進制樹編寫一個波蘭語表示計算器,為此,我必須解析命令行輸入,以便它可以正確地構建二進制樹,然后遍歷它來給出有效的答案。輸入的數學表達式。

為了進行解析,我使用了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

也許你們會看到我錯過的某些東西,或者如果這確實是我程序之外的一個更高的錯誤,在這種情況下,將非常感謝有關報告此位置的指針。

當你說:

  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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM