Checking if input is character or integer.

I just wanted to challenge myself into making a program that only gets the value of a variable, and then, if it is a character and not an integer, open an error message. This is the best I got:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  #include<iostream>
#include<windows.h>
using namespace std;


template <class N>
void check(N a){
if (a>='a' || a<='Z'){
    cout<<"\a";
MessageBox(NULL,"You entered a character, the program requires an integer", "Error", MB_OK);
}
}
int main(){
int n;
cin>>n;
check (n);
}


But the problem is, when I input an integer that is equal to the ASCII value, of one of those characters that are in range of the requirements in the if statement, for example 65, the error message still pops out.
Can't you just do something like this -

1
2
3
4
5
6
int x;
cin >> x;

if (!cin) {
    // input was not an integer
}


http://stackoverflow.com/questions/13440831/how-do-i-check-if-input-is-an-integer-string
Your if condition will always be true. Use && rather than ||. Google truth tables for logical operators.

Only one condition must be true for ||. Anything that is not greater than or equal to 'a' is less than or equal to 'Z', and vice versa.
Last edited on
@TarikNeaj, how would that work all the time, see, for example wouldn't '1' be a char as well, ?
Topic archived. No new replies allowed.