Input validation and Logical OR

I am working with input validation and logical OR. I am trying to make an error message pop up after rejecting input where the first letter in the string is not 0, 1, 2, 3, or 4. However, an error message still pops up even if the first character is 0, 1, 2, 3, or 4. How can I get the program to work as I would like it to?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 #include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	string str;
	cin >> str;
	if (str[0] != '0' || str[0] != '1' || str[0] != '2' || str[0] != '3' || str[0] != '4')
	{
		cout << "Wrong input. Please try again.";	
	}
	return 0;
}
very similar to here:
http://www.cplusplus.com/forum/beginner/209067/

you need logical AND && not OR.

Though as an alternative you might in this case put
 
    if (str[0] <  '0' || str[0] > '4')
I see how Logical AND makes sense since the code block would only execute if it did not find any of the numbers. If my understanding is correct, the code block in my current code will always execute since str[0] can only be one value at a time.
Last edited on
Well, the OR gives a true result when either or both the operands are true. For example, if str[0] has the value '0', the first condition str[0] != '0' will be false. However the condition str[0] != '1' will be true (because '0' is not equal to '1' is a true statement). Thus at least one of the operands will always be true, no matter what the input, and so the OR will result in true.
Yeah, I just edited my post before I saw yours after basically figuring it out. Thank you for your help!
Last edited on
Topic archived. No new replies allowed.