Help in repeating.

Here's the thing:

I want to repeat this problem,
for example:

"Press any key ranging from 1 ~ 5"

I input 6, which is greater than 5, from the given if function.

So the program will output:


"Invalid. Please enter the designated number of the given choices"


What I want to happen is that when I input 6,

the output should be like this:

"Invalid. Please Enter the designated number of the given choices"


and the program will go back to the statement


"Press any key ranging from 1 ~ 5"


and the previous statements will be cleared.



cout << "Press any key ranging from 1 ~ 5"<<endl;
cin >>b;
if (b<1 || b>5)
{
cout << "Invalid. Please enter the designated number of the given choices."<<endl<<endl;
Last edited on
you need a while loop for it to repeat, like something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
double b;
cout << "Press any key ranging from 1 ~ 5"<<endl;
cin >>b;
while (!(b==0)){
	if (b<1 || b>5){
	cout<<"error"<<endl;
	
	}
	cout<<"press any key ranging from 1~5"<<endl;
cin>>b;
}


	






    system("PAUSE"); return 0;
Last edited on
But how will it end? :|
For ex, I need to check whether b<1 || b>5.
If it's False:
if (b==1){
c=c+1;}
else if (b==2){
d=d+1;}
else if (b==3){
e=e+1;}
else if (b==4){
f=f+1;}
else if (b==5){
g=g+1;}


Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
    const char* const prompt = "Press any key ranging from 1 ~ 5: " ;
    const char* const error_msg = "Invalid input\n" ;

    int number ;

    while( std::cout << prompt && !( std::cin >> number && number>0 && number<6 ) )
    {
        std::cerr << error_msg ;
        std::cin.clear() ; // clear a possible error state
        std::cin.ignore( 1000, '\n' ) ; // and throw away invalid chars in the input buffer
    }

    std::cout << "the input is " << number << '\n' ;
}
OR you can use the Switch statement:
(You need to know about functions)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

//(declare this as a function, and declare another tiny function that opens //this function back)
switch (userinput)
{
       case: 1
        // do the 1 processing
       break;
       
       ...

      case: 5
       // do the 5 proseccing

     default:
     cout<<"Invalid number. Please try again";
     tinyfunc();
     break;
}


I dont know if this method works with characters...

Hope I've helped
- Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

double b;

do
{

cout<<"enter a number from 1-5"<<endl;

if (b<1 || b>5)
{
// error message here
}
}
while(b<1 || b>5);
Topic archived. No new replies allowed.