2010-01-16 59 views
13

我在我的第二個OOP類中,我的第一個類是在C#中教的,所以我是C++新手,目前我正在使用cin練習輸入驗證。所以這是我的問題:使用cin的好輸入驗證循環 - C++

是這個循環我構建了一個很好的方法來驗證輸入?還是有一種更常見/可接受的方式呢?

謝謝!

代碼:

int taxableIncome; 
int error; 

// input validation loop 
do 
{ 
    error = 0; 
    cout << "Please enter in your taxable income: "; 
    cin >> taxableIncome; 
    if (cin.fail()) 
    { 
     cout << "Please enter a valid integer" << endl; 
     error = 1; 
     cin.clear(); 
     cin.ignore(80, '\n'); 
    } 
}while(error == 1); 

回答

23

我沒有打開的輸入輸出流異常巨大的風扇。 I/O錯誤並不是很好,因爲錯誤通常很可能。我只喜歡使用異常來減少錯誤條件。

代碼不壞,但跳過80個字符是有點任意的,如果你用循環操作(如果你保留它,應該是bool),錯誤變量不是必須的。您可以將cin中的讀取直接寫入if,這可能更像是一個Perl成語。

這是我的看法:

int taxableIncome; 

for (;;) { 
    cout << "Please enter in your taxable income: "; 
    if (cin >> taxableIncome) { 
     break; 
    } else { 
     cout << "Please enter a valid integer" << endl; 
     cin.clear(); 
     cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
    } 
} 
僅跳過80個字符

除此之外,這些都只是輕微的狡辯,而且是更優選的風格問題。

+0

謝謝,這是更符合我尋找的線路。非常感激。有一個問題,for循環條件(;;)是什麼?不明白。 – Alex

+2

@Alex - 'foo(;;)'意味着永遠循環,就像'while(1)'一樣。如果你不希望你的循環真正循環到永遠,你需要在裏面的一個「break」來終止循環。 –

+0

在這種情況下,我通常會使用(!eof(stdin)),以避免代碼在輸入丟失時變得瘋狂......或者會在這裏拋出異常嗎? – PypeBros

3

難道你不會考慮try/catch語句,只是爲了讓你用來異常處理的概念?

如果不是,爲什麼不使用布爾值而不是0和1?養成使用正確類型的變量的習慣(並根據需要創建類型)

Cin.fail()在http://www.cplusplus.com/forum/beginner/2957/

事實上,在很多地方進行了討論......

http://www.google.com.sg/#hl=en&source=hp&q=c%2B%2B+tutorial&btnG=Google+Search&meta=&aq=f&oq=c%2B%2B+tutorial

你可能會研究其中的一些,並嘗試按照某種方式來解釋爲什麼應該這樣做。

但是,遲早,你應該瞭解例外...

2

一個小問題是錯誤的輔助變量是完全多餘的,並且不需要:

do 
{ 
    cin.clear(); 
    cout << "Please enter in your taxable income: "; 
    cin >> taxableIncome; 
    if (cin.fail()) 
    { 
     cout << "Please enter a valid integer" << endl; 
     cin.ignore(80, '\n'); 
    } 
}while(cin.fail()); 
4
int taxableIncome; 
string strInput = ""; 
cout << "Please enter in your taxable income:\n"; 

while (true) 
{ 
    getline(cin, strInput); 

    // This code converts from string to number safely. 
    stringstream myStream(strInput); 
    if ((myStream >> taxableIncome)) 
     break; 
    cout << "Invalid input, please try again" << endl; 
} 

所以你看我用輸入的字符串,然後將其轉換成一個整數。這樣,有人可以輸入enter,'米老鼠'或任何東西,它仍然會迴應。
另外#include <string><sstream>