#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int main()
{  
   int x;
   cout << "Press the number 1, 2 ,or 3";
   cin >> x;
  
    while (x!=1){
  
        cout<<"Please try to pick a difference selection.";
        cin>>x;
        }
   
   if ((x==1) {
   
        cout<<"\nYou chose ";cout<<x;  
    }
    system("PAUSE");
    
    
    return 0;
}

hey all im new to c++ and just playing around with the while loop and if statements. my question is how can i make it so if the user inputs anything other than 1, 2, or 3 it asks them to try again without crashing. it didnt crash when incorrect small integers were entered but when i put in a char it crashed in an endless loop.

This example uses a do while loop to keep asking for the user input if it is not correct.

A do while loop will enter the loop no matter what the value of the variable that you are checking against is but will check at the end. In this case we do not care what the value of x is when we want the initial input but we want it to be between 1 and 3 in the end.

#include <iostream>
using namespace std;

int main()
{
	int x;
	do
	{
		cout << "Enter a number (1, 2 or 3): ";
		cin >> x;
	}while( x > 3 || x < 1 );
	cout << "You chose " << x << endl;

	return 0;
}

In order to get around the char input endless loop error you need to use try and catch which I would loop up here.

The website that I linked for reference is a very good tutorial/reference page and if you generally know what you are looking for it is easy to look up the usage.

After testing out try and catch I couldn't get it to work and I cannot edit my last post to remove the end part where I tell you to go check that out to solve the problem. However I still recommend that website for reference/tutorials.

I looked around and found this which seems to work from what I have tested.

Just replace the line cin >> x; with the following:

if( !(cin >> x) )
{
	x = 0;
	cin.clear();
	cin.ignore();
}

ok thanks for posting and helping me out.. i'm gonna give that a try tonight when i get to work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.