简体   繁体   中英

C++ Input Validation

Can someone help with my input validation function. I'm validating an integer input. The issue is when a user enters more than one integer my cin.fail() runs for every integer, causing my error to display multiple times. Let me show you what I mean

Here's my code:

#include <iostream>
//#include "Uni.hpp"
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::getline;

int main()
{

bool repeat;
int choice; 
repeat = false;

//Give user options     
cout << "Enter 1:   Print building information" << endl;
cout << "Enter 2:   Print people information" << endl;
cout << "Enter 3:   Assign work to a Student or instructor." << endl;
cout << "Enter 4:   Exit program." << endl;
cin >> choice;



//First check for correct data type integers only in this case 
while (cin.fail())
{
    cout << "Enter only an integer please. Try again." << std::endl;
    cin.clear();
    cin.ignore();
    cin >> choice;
}

//run program until user exits
while (choice != 4)
{
    if (choice == 1)
    {
        cout << "Print building info" << endl;
    }

    if (choice == 2)
    {
        cout << "Print people info" << endl;
    }

    if (choice == 3)
    {
        cout << "Assign work" << endl;
    }

    if (choice > 4)
    {
        cout << "Not a valid choice. Choose " << endl;
    }

    cout << endl;
    cout << endl;
    //give options again 
    cout << "Enter 1:   Print building information" << endl;
    cout << "Enter 2:   Print people information" << endl;
    cout << "Enter 3:   Assign work to a Student or instructor." << endl;
    cout << "Enter 4:   Exit program." << endl;
    cin >> choice;

    //data type validation
    while (cin.fail())
    {
        cout << "Enter only an integer please." << endl;
        cin.clear();
        cin.ignore();
        cin >> choice;
    }

So, if a user were to enter "jjj"; my "Enter only an integer please" is displayed three times. I would only like for it to display once. I can't figure out how to do this. Any ideas?

Test for cin.fail first, and print the message once, then process and clear off the characters in the loop. This will account for eg people typing in "bbb" which will trigger three runs through the loop, but it will only give you the message one time:

    if (cin.fail())
    {
        cout << "Enter only an integer please." << endl;
    }
    //data type validation
    while (cin.fail())
    {
        cin.clear();
        cin.ignore();
        cin >> choice;
    }

You can also move the instructions/input validation code to the top of the while loop, then you don't need to have it repeated outside the while loop to start with

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM