invalid choice problem

closed account (35G3T05o)
I'm trying to dismiss an invalid choice. Everything works fine unless user enters 1. When 1 is entered it does its job then instead of finishing main, it goes to the else clause. Any help would be appreciated.
edit-- Also if a char is entered it goes into an infinite loop.



#include <cstdlib>
#include <iostream>

using namespace std;

int main(){

int n;
loop:
cout << "choose a number between 1 and 2: " << endl;
cin >> n;

if (n == 1){
cout << "good" << endl;
}
if (n == 2){
cout << "still good" << endl;
}
else{
goto loop;
}
system("PAUSE");
return 0;

}

Last edited on
Because your two if statements are separate from each other. I think you're looking for an if/else if block instead.

On a side note, try not to use goto. Leads to spaghetti code :)
closed account (35G3T05o)
Thanks for your reply. If not goto... how should i solve this problem?
Have you learned about loops yet? If so, a while loop could keep it repeating. If you haven't learned about loops, now would be a good time to do so.
closed account (35G3T05o)
I have learned some about while loops but when I try it with a while loop, everything works fine until an invalid char is inputed. At that point i get an iinfinate loop.





#include <cstdlib>
#include <iostream>

using namespace std;

int main(){

int n;
while (n != 1 || n != 2){
cout << "choose a number between 1 and 2: " << endl;
cin >> n;
if (n == 1){
cout << "good" << endl;
break;
}
if (n == 2){
cout << "still good" << endl;
break;
}

}
system("PAUSE");
return 0;

}
closed account (35G3T05o)
Ok i got it to work using "else if." Still working on doing it w/o goto.

#include <cstdlib>
#include <iostream>

using namespace std;

int main(){
loop:
int n;

cout << "choose a number between 1 and 2: " << endl;
cin >> n;

if (n == 1){
cout << "good" << endl;
}
else if (n == 2){
cout << "still good" << endl;
}
else{
goto loop;
}
system("PAUSE");
return 0;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main(){
  int n;
  char nn [256];
  while (n!=1 && n!=2) {
    cout << "choose a number between 1 and 2: " << endl;
    fgets ( nn, 256, stdin ); //solves the problem that users may not input characters
    n = atoi (nn);
  }
  if (n == 1){
    cout << "good" << endl;
  } else if (n == 2) {
    cout << "still good" << endl;
  }
  system("PAUSE");
  return 0;
}
Last edited on
closed account (35G3T05o)
Thanks for reply, after searching for hours, I found this which also worked.
1
2
3
4
5
6
7
8
9
10

if (!cin){
         cin.clear();
         cin.ignore(1000, 'n');
         cout << "Please enter a number" << endl << endl;




Last edited on
Topic archived. No new replies allowed.