-1

I'm still new to C as I'm trying to understand it some more.

Today I was comparing pieces of content from my char array to numbers (see example below) and it didn't seem to work unless I used their respective ASCII code, so my question is:

Is there another way of comparing the content of a char array for example with a number (except for making the number a local variable) ?

Input = 1

char test [10];
scanf("%s", test);
if (test[0] == 1) {
    puts("True");
}

While this one did work

    char test [10];
    scanf("%s", test);
    if (test[0] == 49) {
        puts("True");
    }

Thanks in advance!

Glenndisimo
  • 251
  • 1
  • 7
  • 14

1 Answers1

0

You are "scanning" the input as a string. So you end up with an array of characters.
If you enter the number "1" what you are asking scanf to do is to interpret it as the string "1", and that is why you have the ASCII representation of "1" on your array.

If you want scanf to interpret your input as an integer try:


int test;
scanf("%i", test);
if (test == 1) {
   puts("True");
}

BTW use of scanf is frowned upon as it is not possible to prevent buffer overflows. Then again outside of homework assignments I don't think it is actually used.

Community
  • 1
  • 1
Eli Algranti
  • 8,707
  • 2
  • 42
  • 50