loop question.

How can i loop the question whenever the user inputs an invalid answer.

for example..

/* question #1 */
cout<< "#1. 5+5=?" <<endl<< "A. 10" <<endl<< "B. 2" <<endl<< "C. 3" << "Your answer is.. ";
cin>>ans;
if(ans=='A')
/* valid.. proceed to question 2 */
else if (ans=='B')
/* valid.. proceed to question 2 */
else if (ans=='C')
/* valid.. proceed to question 2 */
else
cout<<"Invalid answer.. do you wish to go back to the previous question? Y/N";
cin>>ans2;
if (ans2=='N');
exit program.
else
/* This is my problem XD.. how can i make it go back to question number 1? */
Last edited on
Use a while loop.

1
2
3
4
while(ans != 'A' && ans != 'B' && ans != 'C')
{
    // code goes here
}
There are a ton of different ways. Dash's will work. Here are two I can think of off the top of my head:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* question #1 */

//while loop
while(1)
{
    cout<< "#1. 5+5=?" <<endl<< "A. 10" <<endl<< "B. 2" <<endl<< "C. 3" << "Your answer is.. ";
    cin>>ans;
    if(ans=='A')
    /* valid.. proceed to question 2 */
    else if (ans=='B')
    /* valid.. proceed to question 2 */
    else if (ans=='C')
    /* valid.. proceed to question 2 */
    else
    {
        //invalid answer
        cout<<"Invalid answer.. do you wish to go back to the previous question? Y/N";
        cin>>ans2;

	if (ans2=='N');
            break; //break out of the while loop
    }
    //valid answer
    //do stuff here
}

//do-while loop
do{
    bool invalid = false
    cout<< "#1. 5+5=?" <<endl<< "A. 10" <<endl<< "B. 2" <<endl<< "C. 3" << "Your answer is.. ";
    cin>>ans;
    if(ans=='A')
    /* valid.. proceed to question 2 */
    else if (ans=='B')
    /* valid.. proceed to question 2 */
    else if (ans=='C')
    /* valid.. proceed to question 2 */
    else{
        cout<<"Invalid Input." << endl;
        invalid = true;
    }
}while(invalid);
the easist way but the dangerouest way: goto sentance maybe worked,but not suggested.
int main()
{
char ans , ans2 ;

A: cout<< "Your answer is.. ";
cin>>ans;
if(ans=='A')
;

else if (ans=='B')
;

else if (ans=='C')
;

else
{
cout<<"go back to the previous question? Y/N";
cin>>ans2;
if(ans2=='N')
return 0 ;
else
goto A ;
}

}
Topic archived. No new replies allowed.