Setting condition for chars.

Hi guys. Thanks for the help earlier. But I have a new problem now. Based on the code , type y to repeat and n to cancel the problem. How can I make a condition where if you type in other chars besides 'y' and 'n' a message will pop-up? I tried applying if statement but the program ended up looping my message over and over again.

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
#include <iostream>
using namespace std;


int main ()
{
	int counter , fnum ;
	char i;
	
	for (;'y';)
	{
	      
	      { 
  	         cout<<"Please enter a positive integer: ";
	         cin>>fnum;
	                     if (fnum > 0)
	                           {
							     for (counter=fnum;counter>0;counter--)
	                               {
			                        if (fnum%counter==0)
	                                cout<<counter<<endl;
	                               }
							   }
							   
						  else if (fnum <=0)
						       { 
						         cout<<fnum<<" is not a positive integer."<<endl;
						       }  
						 
						  	    
	                   
	        cout<<endl<<"Would you like to see the divisors of another integer (y/n)?"; 
	        cin>>i;
	                    
						
	      
           }        
    if (i == 'n')
         break;
    }
	        return 0;
}
Hi there,

Try to use a do/while loop for this one as such:

1
2
3
4
5
6
do {
    //ask question
} while(i == 'y');

//handle any other character than y here


More information on this loop can be found at http://cplusplus.com/doc/tutorial/control/#do

All the best,
NwN
Last edited on
The looping can be a little more concise, consider a do-while:
1
2
3
4
5
6
7
8
char choice;
do
{
  cout << "Would you like to go again (y/n) ? ";
  cin >> choice;
  cin.ignore(80, '\n');  //  Make sure there is nothing in the buffer for next extraction
}
while (choice == 'y'); 


To validate, start a while loop after line 6:
1
2
3
4
5
while (choice != 'y' && choice != 'n')
{
  cout << "Invalid choice, try again: ";
  cin >> choice;
}
Last edited on
Alright guys. Thanks for the guidance. I'll try.
Topic archived. No new replies allowed.