1

この回答を検索しましたが、このエラーを修正する方法を誰も知らないようです。入力を厳密にintにしたい。入力が double の場合は、エラーを送信するようにします。

int creatLegs = 0;
string trash;
bool validLegs = true;
do
{
    cout << "How many legs should the creature have? ";
    cin >> creatLegs;

    if(cin.fail())
    {
        cin.clear();
        cin >> trash; //sets to string, so that cin.ignore() ignores the whole string.
        cin.ignore(); //only ignores one character
        validLegs = false;
    }

    if (creatLegs > 0)
    {

        validLegs = true;
    }

    if (!validLegs)
    {
        cout << "Invalid value, try again.\n";
    }

} while (!validLegs);

ほぼ効きそうです。エラーを送信しますが、次のループに移動した後でのみです。どうすればこれを修正できますか? そして、エラーメッセージがまだ表示されているのに、表示される前にまだ進んでいるのはなぜですか?

4

4 に答える 4

0

この質問にはすでに受け入れられた回答がありますが、整数であるすべての数値を処理するソリューションを提供します。番号。

受け入れられる値の例。これらはすべて数値 4 を表します。

4
4.
4.0
+4
004.0
400e-2

拒否された値の例:

3.999999
4.000001
40e-1x
4,
#include <iostream>
#include <sstream>
#include <cctype>
#include <string>

using namespace std;

bool get_int( const string & input, int & i ) {
    stringstream ss(input);
    double d;
    bool isValid = ss >> d;
    if (isValid) {
        char c;
        while( isValid && ss >> c ) isValid = isspace(c);
        if (isValid) { 
            i = static_cast<int>(d);
            isValid = (d == static_cast<double>(i));
        }
    }
    return isValid;
}

int main( int argc, char *argv[] )
{
    int creatLegs = 0;
    bool validLegs = false;

    do
    {
        string line;
        do {
            cout << "How many legs should the creature have? ";
        } while (not getline (cin,line));

        validLegs = get_int( line, creatLegs );

        if (creatLegs <= 0)
        {
            validLegs = false;
        }

        if (not validLegs)
        {
            cout << "Invalid value, try again." << endl;
        }

    } while (not validLegs);

    cout << "Got legs! (" << creatLegs << ")" << endl;

    return 0;
}

厳密に整数が必要な場合 (小数ピリオドや科学表記法を使用しない)、次の単純なget_int関数を使用します。

bool get_int( const string & input, int & i ) {
    stringstream ss(input);
    bool isValid = ss >> i;
    if (isValid) {
        char c;
        while(isValid && ss >> c) isValid = isspace(c);
    }
    return isValid;
}
于 2015-04-03T17:55:22.870 に答える