簡體   English   中英

使用 cin 的良好輸入驗證循環 - C++

[英]Good input validation loop using cin - C++

我在上我的第二堂 OOP 課,我的第一堂課是用 C# 教授的,所以我是 C++ 的新手,目前我正在使用 cin 練習輸入驗證。 所以這是我的問題:

這個循環是我構建的一種很好的驗證輸入的方法嗎? 或者有更常見/接受的方式嗎?

謝謝!

代碼:

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);

我不太喜歡為 iostreams 打開異常。 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 個字符外,這些只是小問題,更多的是首選風格。

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;
}

所以你看到我使用字符串作為輸入,然后將其轉換為整數。 這樣,有人可以輸入回車、“米老鼠”或其他任何東西,它仍然會響應。
還有 #include <string><sstream>

你可能不考慮 try/catch,只是為了讓你習慣異常處理的概念?

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

http://www.cplusplus.com/forum/beginner/2957/也討論了 Cin.fail()

其實很多地方...

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

您可能會研究其中的一些,並嘗試遵循為什么應該以某種方式完成工作的解釋。

但是,遲早你應該了解異常...

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

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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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