2014-09-13 73 views
2

我一直在使用StanfordCPPLib通過Eric S.Roberts的「C++編程抽象」工作,但simpio.h中的這個函數突然給我帶來了悲傷。它過去運行良好,但現在無論輸入什麼數字/字母/等,它都會給我「非法整數格式,請重試。」爲什麼這個簡單的getInteger函數會導致流失敗?

我嘗試了通過從if語句中刪除!stream.fail()位進行一些調試,它的工作原理與魅力一樣......但使用此函數的一部分是檢查失敗狀態。嗯。

我記得上次使用這個庫做的唯一實質性的事情,從10.8

升級到OSX 10.9我缺少什麼?提前致謝!

/* 
* Implementation notes: getInteger, getReal 
* ----------------------------------------- 
* Each of these functions reads a complete input line and then uses the 
* <sstream> library to parse that line into a value of the desired type. 
* If that fails, the implementation asks the user for a new value. 
*/ 

int getInteger(string prompt) { 
    int value; 
    string line; 
    while (true) { 
     cout << prompt; 
     getline(cin, line); 
     istringstream stream(line); 
     stream >> value >> ws; 
     if (!stream.fail() && stream.eof()) break; 
     cout << "Illegal integer format. Try again." << endl; 
     if (prompt == "") prompt = "Enter an integer: "; 
    } 
    return value; 
} 
+0

這對我很好。 – Galik 2014-09-13 07:50:04

+0

它也適用於:https://ideone.com/Lki2dG – Omid 2014-09-13 08:00:07

+0

[轉載](http://melpon.org/wandbox/permlink/DeTYVed7C8QLQGYX)與clang/libC++。 – 2014-09-13 09:07:43

回答

1

考慮一個字符串"123"通過getline取出,然後放入istringstream

stream >> value將提取123,並在流上設置eofbit

然後發生stream >> ws。指定ws首先構造一個sentry對象,如果is.good()false,則指定其構造函數的調用is.setstate(failbit) - 它是eofbit的設置。因此,stream.fail()true!stream.fail() && stream.eof()false,並且您的代碼打印出「非法整數格式」。

在這種情況下,libstdC++的實現沒有設置failbit,這看起來不合格。

一個簡單的解決方法是在line末尾添加尾隨空格:

istringstream stream(line + " "); 

這確保了ws將始終沒有eofbit集調用,從而使sentry構造將不設置failbit

相關問題