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?