How to handle wrong type of input in switch statement

Hello!

My program runs successfully but when the user enters characters the program exits. I want to give the user another try and go back to while statement. I tried many things.
If (!cin.good()){
cin.clear();
cin.ignore(300, '\n')
cin.number;
}
makes sense to me but not working
Here is my entire code:

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
#include <math.h>
#include <cstdlib>
using namespace std;
//int number(int);
int main()
{
char filename[300];
cout << "Please enter filename.extension to create: ";
cin >> filename;
if (cin.eof())
exit(1);
fstream inFile(filename, ios::in);
int number;
int ct = 0;
int ct1 = 0;
int ct2 = 0;
int ct3 = 0;
int ct4 = 0;
int ct5 = 0;

double sum;
double sum1{ 0 };
double sum2{ 0 };
double sum3{ 0 };
double sum4{ 0 };
double price;

if (!inFile)
cout << "Could not open file. Terminating." << endl;
else {

while (inFile >> number, !inFile.eof()) {
cout << number << endl;

++ct;


if (number == 1) {

++ct1; price = 2.99;

sum1 += price;
}

if (number == 2) {

++ct2; price = 7.99;
sum2 += price;

}

if (number == 3) {
++ct3; price = 3.99;
sum3 += price;
}
if (number == 4) {
++ct4; price = 4.99;
sum4 += price;
}


sum = sum1 + sum2 + sum3 + sum4;
}
int n=number ;
cout << "Enter the number of the game from 1 to 4 and hit <Enter>" << endl << "Enter eof to exit" << endl
<< "Enter ctrl^z to get the total price and count" << endl;

while (cout << "The number of the game: ", cin >> n) {


if (!cin.eof() && cin.good()) {
switch (n) {

case 1:
cout << "Number of Mario Brothers sold: " << ct1 << endl;
cout << "Total is: " << sum1 << endl;
break;
case 2:
cout << "Number of Partners Bridge sold: " << ct2 << endl;
cout << "Total is: " << sum2 << endl;
break;
case 3:
cout << "Number of Minesweeper sold: " << ct3 << endl;
cout << "Total is: " << sum3 << endl;
break;
case 4:
cout << "number of Sudoku sold: " << ct4 << endl;
cout << "Total is: " << sum4 << endl;
break;

default:

cout << "Invalid input please try again " << endl;

++ct5;
break;



}

}


}



if (cin.eof()) {
cout << "gross total is: " << sum << endl;
cout << "Total number of games sold is: " << ct << endl;
cout << "Total invalid inputs: " << ct5;
cout << endl;
}
}

return EXIT_SUCCESS;
}

Last edited on
bool stop = false;
do
{
switch

default
{
… etc
stop = true; //they screwed up input, don't stop.
}

}while(stop); //its true, they messed up, go again, else stop.
Last edited on
Topic archived. No new replies allowed.