I am doing an assignment and I am a complete novice, in my assignment I have to get the user to input one of two words and then validate their input, i assume I have to set it as a string, however when i do this it doesn't prevent them from putting a number in, could someone please explain to me why the top half of this code works however the bottom half which appears to say the same this doesn't:
#include <iostream>
using namespace std;
int main ()
{
int x = 0;
while ((x < 1) || (x > 3)) {
cout << "Enter either 1, 2 or 3: ";
if (!(cin >> x)) {
cin.clear();
cin.ignore(255,'\n');
}
if ((x < 1) || (x > 3)) {
cout << "Input out of range. Please try again. " << endl;
}
}
return 0;
}
This is the second version of the code:
#include <iostream>
using namespace std;
int main ()
{
int x = 0;
while ((x != 1) || (x != 2) || (x != 3)) {
cout << "Enter either 1, 2 or 3: ";
if (!(cin >> x)) {
cin.clear();
cin.ignore(255,'\n');
}
if ((x != 1) || (x != 2) || (x != 3)) {
cout << "Input out of range. Please try again. " << endl;
}
}