Programming

int main()
{
int x;

cout << " Please choose between number 1 or 2 " << endl;
cout << " To enter Zoo enter 1 ! " << endl;
cout << " To NOT enter Zoo enter 2 ! " << endl;
cin >> x;
if ( x == 1 )
{
cout << " You have entered the zoo " << endl;
}
else if (x<0||x>2)
{
cout << "That is an invalid number. Please re-run the progra againm" << endl;
}
else if( x == 2 )
{
cout << " You have decided not to take up the challenge, see you again bye ! " << endl;
}

return 0;
}

Hi ! The question goes like this, A boy name Tom has 2 choice, Enter 1 to go Zoo or Enter 2 to not enter zoon. What if the Tom enters a number -1 ? I know the statment will say " That is an invalid number. Please re-run the program again". How do I loop this statement to ask Tom to input the number 1 or 2 without having to compile and re-run my program ?
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
#include <iostream>
#include <string>
#include <limits>

int main(int argc, char ** argv)
{
  int what = 0;
  
  std::cout<<("Write 20 in the console\n");
  std::cin>>what;
  
  while(what != 20 || std::cin.fail())
  {
      if(std::cin.fail())
        std::cout<<"Invalid input\n";
      else
        std::cout<< what << char(0x20) << "isn't the correct number!\n";
        
      std::cin.clear();
      std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
      std::cin>>what;
  }
  
  std::cout<< what << char(0x20) << "is the correct number.";
  return 0;
}



Write 20 in the console
25
25 isn't the correct number!
xabc
Invalid input
20
20 is the correct number.
Last edited on
closed account (48T7M4Gy)
A simple alternative to consider. (But be careful this assumes all input will be integers. Enter a character, string or decimal and the program will bomb.)

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
#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    
    cout << " Please choose between number 1 or 2 " << endl;
    cout << " To enter Zoo enter 1 ! " << endl;
    cout << " To NOT enter Zoo enter 2 ! " << endl;
    
    while (cout << "Now enter no: " && cin >> x)
    {
        if ( x == 1 )
        {
            cout << " You have entered the zoo " << endl;
        }
        else if( x == 2 )
        {
            cout << " You have decided not to take up the challenge, see you again bye ! " << endl;
            break;
        }
        else
        {
            cout << "That is an invalid number. Please re-run the progra againm" << endl;
        }
    }
    
    return 0;
}
Thankyou so much ! I find it really helpful :)
Topic archived. No new replies allowed.