Code:
#include <iostream>
using namespace std;
int main()
{
int first;
char dash;
int last;
char choice;
for ( ; ; )
{
system("cls");
cout << "Enter a range of numbers\n"
<< "(ex: 1-10)" << endl;
cin >> first >> dash >> last;
while (dash != '-')
{
cout << "Invalid range" << endl;
cin >> first >> dash >> last;
}
while (cin.fail())
{
cout << "Invalid range" << endl;
cin >> first >> dash >> last;
}
for (int i = first; i <= last; i++)
cout << i << endl;
cout << "\nWould you like to enter another range?\n"
<< "(Y/N)" << endl;
cin >> choice;
if (toupper(choice) == 'N')
exit(EXIT_SUCCESS);
}
return 0;
}
Why does the program go crazy when an invalid range is entered?
It's suppose to just say "Invalid range" and ask the user to re-enter another range, but it displays "Invalid range" infinitely and never reaches the cin statement.
Code:
while (cin.fail())
{
cout << "Invalid range" << endl;
cin >> first >> dash >> last;
}