用于检查用户输入是否正确无效的功能

时间:2017-03-04 19:10:40

标签: c++

我已经创建了一些C ++代码,该代码应该检查用户的输入是否正确但是我的工作方式并不完全正常。无论何时首先输入一个整数,然后输入几个字符,终端垃圾邮件你想再次尝试y / n几次。我试图限制它输出的次数,但没有任何效果。

#include <iostream>
#include <limits>

using namespace std;

int again()
{

    char yorn = 'q';

    cout << "\n Would you like to run this program again? y/n: ";
    cin >> yorn;

    if (cin.fail()) {

        int dof1 = 1; // dof1 stands for don't overflow 1
        for (int i = 0; i < dof1; i++) {
            cout << "ERROR -- You did not enter a valid symbol";
            // get rid of failure state
            cin.clear();
            // discard 'bad' character(s)
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            bool check = again();
            if (check == true) {
                check = false;
                return again();
            }
            else
                return 0;
        }
    }
    switch (yorn) {

    case 'y':
        return true;
        break;

    case 'n':
        return false;
        break;

    default:
        return again();
        break;
    }
}

int main()
{

    int choice = 0;
    cout << "\nWelcome to the Weight Tracker! Type 000 at any time to exit\n"
         << "Choose the option you would like to use below \n"
         << "1)  \n"
         << "2)  \n"
         << "3)  \n"
         << "Option selected: ";
    cin >> choice;
    if (cin.fail()) {

        int dof2 = 1; // dof2 stands for don't overflow 2
        for (int i = 0; i < dof2; i++) {
            cout << "ERROR -- You did not enter an integer";
            // get rid of failure state
            cin.clear();
            // discard 'bad' character(s)
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            bool check = again();
            if (check == true) {
                check = false;
                return main();
            }
            else
                return 0;
        }
    }
    switch (choice) {

    case 1:
        cout << " use later";
        break;

    case 2:
        cout << " use later";
        break;

    case 3:
        cout << " use later";
        break;

    default:
        cout << "ERROR -- Input invalid \n";
        bool check = again();
        if (check == true) {
            check = false;
            return main();
        }
        else
            return 0;
        break;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

您缺少一个cin.ingnore

default:
    cout << "ERROR -- Input invalid \n";
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); // ADD this line
    bool check = again();

说实话。这段代码很乱。请删除它的递归。