2010-09-03 56 views
0

如果我給這個程序一個字符串在輸入它給我一些非常奇怪的輸出。我該如何處理這個問題?我想簡單地說明領事上有錯誤。奇怪的輸出與簡單的算術C++

#include <cstdlib> 
#include <iostream> 

using namespace std; 

int main() 

{ 
    cout << endl; 
    cout << "Homework (out of 70 pts): " ; 
    int HW ; 
    cin >> HW ; 

    cout << "Midterm (out of 100 pts): " ; 
    int MT ; 
    cin >> MT ; 

    cout << "Final (out of 100 pts): " ; 
    int F ; 
    cin >> F ; 
    cout << endl; 

    int S; 
    S = HW + MT + F; 



    cout << "Score:  " << S << endl; 
    cout << endl; 

    system("pause"); 
} 
+2

究竟發生了什麼奇怪的事情,你在控制檯上發生了什麼錯誤? – viaclectic 2010-09-03 19:12:20

+0

你是說你輸入了一個數字輸入「foo」,並得到奇怪的結果嗎? – 2010-09-03 19:13:45

+0

可能重複[如何驗證數字輸入C + +](http://stackoverflow.com/questions/514420/how-to-validate-numeric-input-c) – 2010-09-03 19:46:48

回答

4

當你輸入一個值cin不期待,比如字符串,而不是一個數字,什麼都不會被讀入您的變量和cin將設置一個錯誤標誌,該標誌將阻止任何進一步的輸入。有關同一主題,請參閱my answer to another question