2017-03-02 138 views
0

當代碼運行時,FtoC()函數中的cin函數被忽略,而ctemp的值默認爲0。我已經得到了代碼運行期望使用其他代碼(不同的循環),但我真的很想了解這種錯誤的機制,並得到這樣做的工作。Cin不會暫停(忽略)用戶輸入

#include <cstdlib> 
#include <iostream> 

using namespace std; 

void threeint(); 
void FtoC(); 

int main() 
{ 
    threeint(); 
    FtoC(); 
    return 0; 
} 

void FtoC() 

{ 
    double ctemp = 0, ftemp = 0; 

    cout << "Please enter the temperature in Celsius which you would like to be\ 
      converted to Fharenheit." << endl; 

    cin >> ctemp; 

    ftemp = ((ctemp * (9/5)) + 35); 

    cout << ctemp << " degrees celsius is " << ftemp << " in fahrenheit" << endl; 
} 


void threeint() 
{ 
    int x = 0, bigint = 0, smlint = INT_MAX, avgint = 0, index = 0; 

    cout << "Input as many integers as you like and finalise by entering any 
      non-integer input" << endl; 

    while (cin >> x) 
    { 
    if (x > bigint) 
     bigint = x; 
    if (x < smlint) 
     smlint = x; 

    ++index; 
    avgint += x; 
    } 

cout << "The largest integer is " << bigint << ".\t" << "The smallest 
     integer is " << smlint << ".\t"; 

cout << "The average of all input is " << (avgint/index) << endl; 
} 
+1

如果'double'或'int'提取失敗,您從不檢查'cin'的狀態。 –

+0

無關但是(9/5)'不會做你認爲它做的事。 (提示:那個結果恰好是1,如果你感到驚訝,[見這裏](http://mathworld.wolfram.com/IntegerDivision.html)) – Borgleader

回答

0

「壞讀」後,您的cin處於壞輸入狀態。您應該跳過壞輸入,並重新嘗試讀取

std::cin.clear(); 
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Skip bad input 
0

我會首先回答你的問題之前清除它的標誌。你的cin不會等待輸入的原因是因爲cin沒有被重置爲在輸入錯誤後接受一個新的值(比如爲你的輸入輸入一個字母)。爲了克服這個問題,你必須清除輸入並忽略輸入的任何錯誤輸入。這可以通過添加下列幾行程序進行:

cin.clear(); // clears cin error flags 
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignores any invalid input entered 

的IOS ::明確設定了流的內部錯誤狀態標誌的新值。標誌的當前值被覆蓋:所有位由狀態中的那些代替;如果state是goodbit(它是零),所有的錯誤標誌都被清除。

這是直接從CPlusPlus.com引用;爲cin.clear()。

cin.ignore()從輸入序列中提取字符並丟棄它們,直到n個字符被提取,或者一個比較等於delim。如果達到文件結束,函數也會停止提取字符。如果提前達到(在提取n個字符或查找分隔符之前),該函數將設置eofbit標誌。

這是直接引自CPlusPlus.com;爲cin.ignore()。

這兩個引用給出了一個深入的分析,以及提供的鏈接,2個函數如何工作。


一對夫婦的其他事情在程序中指出的:

首先,當你做9/5,你正打算爲值是1.8。但是,由於您要分割兩個整數值,編譯器會將最終結果保留爲na int;因此,在你的代碼中9/5 = 1。爲了解決這個問題,你的分裂操作的divide或divisor需要是float類型的。最簡單和最簡單的方法是做9.0/5或9/5.0。這樣,編譯器就知道你想將最終結果作爲浮點值。您也可以使用鑄造,但是,添加小數點更容易,更簡單。

其次,我不確定這個錯誤是否只在你已經發布的代碼中,因爲你說你的編譯完美,但你的cout語句中的一些字符串沒有用撇號,至少在你發佈在這裏的代碼中。一個典型的例子是你的代碼:

cout << "The largest integer is " << bigint << ".\t" << "The smallest 
    integer is " << smlint << ".\t"; 

上帝保佑你!