Check either its a char or an integer
this is an integer array:
int values[] = { 75, '*', 5,'-' };
for(i=0 ; i<size ; i++){
// Here
}
how to check if 开发者_运维百科the values[i]
is an integer or an operation ??
maybe the value equals the Ascii of an operation,, how to deal with it in this case??
You can't. As for as the compiler is concerned, the constants 42
an '*'
are one and the same. In the compiled object code, they're both represented as the integer 42.
If you need to differentiate between integers and characters, either use a boolean flag or enum indicating the type of the value, or keep your integers and characters in separate arrays.
Note that in C++, but not in C, there is a slight difference: 42
has the type int
, whereas '*'
has the type char
, so you can differentiate this fact using overloaded functions or templates.
That's a dangerous road to go down. The array in your example will translate (during compilation) into:
int values[] = {75, 42, 5, 45};
So when you see the number 42... what is it? Is it the '*'
character, or did you actually mean the number 42
?
You can't rely on typecasting, either, because all your values will be cast to int
s, since they're stored in an integer array. Your best bet is to make a struct that holds both type and value, like so:
typedef struct
{
int type; //0 for int, 1 for operator, and so forth.
int value; //holds either a character code or an integer value
//you could use a union here, if you felt it would make things cleaner...
} Token;
Then checking to see what type a token is is simply a matter of looking at token.type
.
Hope this helps!
PS: The cheating answer would be to use a dynamically typed language. Lots less work on your part, but slower, and I don't know if it's an option for you.
Your array elements cannot be simple integers. Try this instead:
enum ElementType {INTEGER, OPERATION};
struct ArrayElement {
enum ElementType etype;
int evalue;
};
struct ArrayElement values[] = {
{INTEGER, 75}, {OPERATION, '*'}, {INTEGER, 5}, {OPERATION, '-'}
};
for (i = 0; i < sizeof values / sizeof *values; i++) {
/* Here */
switch (values[i].etype) {
default: printf("unrecognized type. value is %d.\n", values[i].value);
break;
case INTEGER: printf("INTEGER with value %d.\n", values[i].value);
break;
case OPERATION: printf("OPERATION with value '%c'.\n", values[i].value);
break;
}
}
精彩评论