Reputation:
I'm using scanf to input numbers and +,-,/ operators into a stack.
int scan = 1;
char * p = malloc(sizeof(char)*5);
while (scan = 1) {
scanf("%1s", p);
if(p>='0' && p<='9'){
push(stack, p);
print(stack);
}
}
Why does it never meet the condition? How can you compare strings?
Upvotes: 0
Views: 1324
Reputation: 29266
if(p>='0' && p<='9'){
p
is a char*
, '0'
is a char. Your compiler should have warned you about comparing incompatible types. Use *p
instead (same applies to '9
' obviously). In my head *p
gets read as "contents of p" (in this context)
In the more general case, use strcmp()
to compare strings.
If your compiler did warn you about the bad compare: take it on board, most compiler warnings should be listened to and not ignored. If your compiler didn't warn you look up how to enable all the warnings.
Upvotes: 1
Reputation: 48121
Well, if what you want to do is test whether the first character of the string is between '0' and '9', you should do:
(*p >= '0' && *p <= '9')
But if you want to compare strings as strings, the old school C library function for that is strcmp
. I'm sure these days there are lots of other libraries that may offer more functionality.
Upvotes: 2