some errors ... please give me a solution...

if i accidentally enter "a" then it will be the run time error... how to solve??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include<iostream>
using namespace std;
int main ()
{
	int option;
	do 
{
	cout << string(34,' ') << "Nu1.Bakery" <<string(35,' ') << endl;
	cout << "1.New Order" << endl;
	cout << "2.Cakes Types" << endl;
	cout << "3.Order Summary" << endl;
	cout << "4.Exit" << endl;
	cout << "Please choose the option :";
	cin >> option;
	
}	while (option <= 4 || option >= 1);

	return 0;
}
replace
 
 int option;

With
 
char option;

And the (while) should be
 
 while (int (option)>=49 && (int) option<=52)
closed account (28poGNh0)
@coder1 why complixity while (int (option)>=49 && (int) option<=52
why not while(option >='1' && option<='4');

// Well cin goes through a failed stat ,and will goes on untill the error flag and buffer are reset.
// There is a solution for that ,by adding cin.clear();cin.ignore(); after your cin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# include <iostream>
using namespace std;

int main ()
{
    int option;

	do
    {
        cout << string(34,' ') << "Nu1.Bakery" <<string(35,' ') << endl;
        cout << "1.New Order" << endl;
        cout << "2.Cakes Types" << endl;
        cout << "3.Order Summary" << endl;
        cout << "4.Exit" << endl;
        cout << "Please choose the option :";
        cin >> option;

        cin.clear();
        cin.ignore();

    }while(option <= 4 || option >= 1);

	return 0;
}


also you must alter while(option <= 4 || option >= 1); with while(option <= 4 && option >= 1); otherwise dont expect to get out from your do while loop

finaly I suggest you take @coder1 methode
Last edited on
@ Techno01:

Im sorry but i dont know the method you listed above
I just wanted to offer him an easy method to do it.
Thanks for the method it would be handy in many cases.
There is a logical issue. '4' is supposed to mean "exit". In the examples above, every invalid input does direct exit. A more intuitive UI would ignore every invalid input, and act only with the four allowed.


PS. An another recent thread has exactly the same issue of "allow only  [1-4]".
Topic archived. No new replies allowed.