-2

I have made this little test program in c on my raspberry pi model b.

It compiles without errors, however, the if statement never works:

 #include <stdio.h>
 #include <unistd.h>

int main(int argc, const char * argv[])
{
    char *test = 0;
    printf("Alpha or Beta\n");
    scanf(" %s", test);
    if (test == "Alpha")
    {
        printf("This is string one test\n");
        printf("This is string two test\n");
    }
    else
    {
        printf("An error has occured\n");    
    }
    return 0;
}

For example: I will type Alpha and it will always give me the error has occurred message.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
benpete420
  • 43
  • 1
  • 2
  • 10

1 Answers1

0

You can't compare strings using "==". Use the strcmp function instead. http://en.cppreference.com/w/c/string/byte/strcmp

rost0031
  • 1,894
  • 12
  • 21
  • Even when I use numbers (I also changed it to int, and did all of the %d and &test and stuff like that), and it still doesn't work for me. – benpete420 May 28 '15 at 21:04
  • 1
    That's because your pointers (which is what you're checking) will not be the same since they are pointing to different memory addresses. I promise you that if/else works just fine. – rost0031 May 28 '15 at 21:06
  • @roost0031 would this be ok? char test[10] – benpete420 May 28 '15 at 21:10
  • Yes, but you have to make sure to still use strcmp() and not "==". Also, don't forget to null terminate your string. – rost0031 May 28 '15 at 21:10
  • Could you add a new answer with that code fixed? (If it is too much trouble I understand) – benpete420 May 28 '15 at 21:11
  • Why don't you give it a shot? It's your homework. You won't learn anything if I just do it for you. If you run into trouble, then ask for help. It's pretty inappropriate to ask StackOverflow to do stuff for you and you will get downvoted mercelessly. – rost0031 May 28 '15 at 21:13
  • Sorry, ok. (I haven't been here much). Could you please explain how comparing strings would fix my problem? – benpete420 May 28 '15 at 21:15
  • Because currently, the if/else will always select the else path and will always print "error has occurred". If you use the function as suggested, it should take the "if" path. – rost0031 May 28 '15 at 21:17
  • 1
    Thanks! That fixed it – benpete420 May 28 '15 at 21:20