I am trying to write a simple code with if condition.
If(x==1||x==2||x==3)
{
found true;
}
else
{
cout<<"Please provide the correct input";
cin<<input;
}

Based on this i need to have another condition:
if(found)
{
cout<<"Enter number";
cin>>no;
}

The problem with the code is when i am entering invalid x value it is coming to else loop and again i am assigning the correct value.But when it so coming to the second condition it is not waiting for the user input.It is immediately terminating from the program.Let me know where i am doing wrong.

I don't know what you're trying to do but shouldn't it be:

bool found = false;

If(x==1||x==2||x==3)
{
   found = true;
}else{
cout<<"Please provide the correct input";
cin >> input;
}

if(found)
{
cout<<"Enter number";
cin>>no;
}

Also, put your code in tags!

Edited 5 Years Ago by phorce: n/a

The problem is that after you get the correct input from the user you are not setting the found flag to true. Add a line to set found to true in your else statement. As a side note the best way to get input from the user that could be wrong is to do it with a loop. The reason for this is that even though you get an input in your else statement that new input could also be wrong.

I tried to do it in a for loop.But i am not sure how to provide the condition.

Well you could use a while loop like this

int number = 0;
while(number != 1 && number != 2 && number != 3)
{
    cout << "Please enter a valid number: ";
    cin >> number;
}

Hello Nathan,
I tried ur code.When i am giving the correct input second time still the loop is repeating as invalid input since the first cin value is not erased.So itried with cin.clear() in while loop as first statement but no use.

I have a data member const std::string& n.When i give an invalid input the string should be cleared so that it can take the correct input later on.I have tried the below codes:
n.clear();//not compatible with member function.
type("");//not working.
type.str("");
Let me know what should be the correct way to reset the string.

This article has been dead for over six months. Start a new discussion instead.