Checking to see if integer is a character.

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

int main()
{
int x;

cout << "Enter character:";
cin >> x;
if(char(x)=='+')
{
cout << "This is addition";
}
else
{
cout << "This is not addition";
}
return 0;
}


If i type in:

+

How come it says that "this is not addition?
Change from
int x;
to
char x;

This will read to the variable "x" in "Character mode" (As text) and not as a number.
Using int will read to "x" as "Number mode".

(Terminology's made up, for simplicity's sake)
char(x) returns the character with the ASCII code number x. So, just if you enter 43, which is the ASCII code for '+', you will get "This is addition".
You cannot store characters in int data type, just ASCII code representing characters. Use char data type for character handling.
Last edited on
I want to keep the data type int. But I want to write a program that determines whether the user did enter a plus sign instead of a regular number. Is there a way to check to see if a data type int was entered as an addition sign?
I don't think so,entering a non-number value instead of a integer, will cause cin to fail. Instead, you can use char data type and check if character is number,or if it's non-number.
http://www.cplusplus.com/reference/cctype/
Last edited on
The slightly tricky part is that +6 is valid input of a number.

Perhaps, something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

int main()
{
    int x ;
    char c ;
    bool number = false ;

    std::cout << "Enter either a number or a character:";

    std::cin >> c ; // read a char

    // put it back and try to read a number
    std::cin.putback(c) ;
    if( std::cin >> x ) number = true ;
    else
    {
        std::cin.clear() ; // clear the failed state (to enable more input)
        x = c ;
    }

    if(number) std::cout << "This is the number " << x << '\n' ;

    else if( x == '+' ) std::cout << "This is addition\n" ;

    else std::cout << "This is something else\n" ;
}
Topic archived. No new replies allowed.