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;
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;
}
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;
} elseif (n == 2) {
cout << "still good" << endl;
}
system("PAUSE");
return 0;
}