I am having trouble with a program I have written, it allows the user to enter starting number, end number and number per line, the problem is I want to add in a check to see if the user enters a character instead of an integer. The proram works and is executable but when you enter a letter for example it goes into an infinite loop. Here is the code:
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
bool NoEnter = true;
bool CarryOn = true;
int StartNo = 0;
int EndNo = 0;
int NoPerLine = 5;
int TestStuff = 0;
string CO;
while(CarryOn)
{
NoEnter = true;
while(NoEnter)
{
StartNo = 0;
EndNo = 0;
NoPerLine = 5;
TestStuff = 0;
cout << "Starting number: ";
cin >> StartNo;
cout << "End number: ";
cin >> EndNo;
cout << "Number per line: ";
cin >> NoPerLine;
if(StartNo <=EndNo){}
else
{
cout << "Enter an end number greater than or equal to start number\n";
TestStuff = TestStuff + 1;
}
if(NoPerLine >= 1){}
else
{
cout << "Numbers per line must be greater than 1\n";
TestStuff = TestStuff + 1;
}
if(TestStuff == 0)
{
NoEnter = false;
}
}
cout << "\n";
for(int i = StartNo; i<=EndNo;i++)
{
cout << i << " ";
if(StartNo == NoPerLine)
{
if(i % (NoPerLine) == 0 && i!=NoPerLine)
{
cout << "\n";
}
}
else
{
if(i % (NoPerLine) == 0)
{
cout << "\n";
}
}
}
cout << "\n";
cout << "\nWould you like to go again? Y or N: ";
cin >> CO;
if(CO == "N" || CO == "n")
{
CarryOn = false;
}
else
{
cout << "\n";
}
}
}
Any help would be greatly appreciated, this is an assignment for school but I just need help with that one thing, I have the thing up and running, hopefully I can get help on this one. Thanks in advance.
Input validation: http://www.cplusplus.com/forum/beginner/18258/#msg92955
The part where my example complains is where you should recognize a non-numeric input. (That is, if cin is not good() after attempting to read a number.