簡體   English   中英

如何使用 cin.fail() 在 C++ 中驗證字符串?

[英]How do you use cin.fail() to validate a string in C++?

我正在嘗試驗證應該是字符串的輸入是否作為字母字符串而不是數字輸入。 這是我所擁有的:

    // Manufacturer
    cout << "Enter the manufacturer: " << endl;
    string newManufacturer;
    cin >> newManufacturer;
    while (cin.fail()) {
        cout << "Error! Invalid input." << endl;
        cout << "Enter the manufacturer: " << endl;
        cin.clear();
        cin.ignore(256, '\n');
        cin >> newManufacturer;
    }
    obj1.setManufacturer(newManufacturer);

我建議您使用以下代碼:

#include <iostream>
#include <string>
#include <cctype>

int main()
{
    std::string newManufacturer;

    for (;;) //infinite loop
    {
        //prompt user for input
        std::cout << "Enter the manufacturer: " << std::flush;
        std::cin >> newManufacturer;

        //fall through to label "input_invalid" if stream extraction failed
        if ( !std::cin.fail() )
        {
            //verify that input consists completely of letters
            for ( char &c : newManufacturer )
            {
                if ( !std::isalpha( c ) )
                    goto input_invalid;
            }
            break;
        }

    input_invalid:
        //print error message and prepare stream for next input attempt
        std::cout << "Error! Invalid input." << std::endl;
        std::cin.clear();
        std::cin.ignore( 256, '\n' );
    }

    std::cout << "The input is valid." << std::endl;

    //do something with the input
}

通常,如果可以避免使用goto語句,則不應使用它們。 但是,我認為沒有辦法避免它,而不會導致大量的代碼重復。

暫無
暫無

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

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