Irina
Irina

Reputation: 1598

C - Comparing string literal with character array

I am new to C and am still a bit confused about how to use strings via character arrays.

In my C program, I am accepting commands from the user:

char command[20];
scanf("%s",command);

Of course, afterwards I want to figure out what command they typed (something similar to: "if (command == "hello"), then do something"). I know this is not possible in C because I am comparing a string literal to a character array, but what would be a good way to it? I have tried using strcmp(command, "hello") and still got errors.

Any advice you can provide would be very appreciated. Thank you!

Upvotes: 8

Views: 78814

Answers (4)

JackCColeman
JackCColeman

Reputation: 3807

I have written a complete version of what I think you are trying to do:

    #include <string.h>
    void main()
    {

       char command[20];
       scanf("%s",command);

       // command and "hello" can be less than, equal or greater than!
       // thus, strcmp return 3 possible values
       if (strcmp(command, "hello") == 0)
       {
          printf("\nThe user said hello!");
       }

    }

Several people have commented about using scanf and they are correct, except that a new programmer has to start somewhere in learning this stuff, so don't feel too bad we are all learning...

Hope this helps.

Upvotes: 15

qunying
qunying

Reputation: 418

When talking about string in C, it normally takes two forms: 1. a character array, 2. a character pointer. Most of the time, they are interchangeable. For example:

char *cmd_ptr = "command1";
char cmd_array[20] = "command2";
printf ("cmd1: %s cmd2: %s\n", cmd_ptr, cmd_array);

The main difference for the above definition is that for cmd_ptr you could not change its content like cmd_ptr[0] = 'a'; for cmd_array you could change any element in the array.

But you could do cmd_ptr = cmd_array; then you could make changes through cmd_ptr as it points to the same location as cmd_array.

Upvotes: 0

gravitas
gravitas

Reputation: 703

strcmp returns 0 when the strings are the same. I have code that uses strcmp comparing character arrays to string literals, and I was quite confused when it wasn't working. Turns out it was wrong for me to assume it would return 1 when the string are the same!

Maybe you've made the same mistake?

Upvotes: 7

spartygw
spartygw

Reputation: 3462

I think this is a perfect starting point for you:

http://www.wikihow.com/Compare-Two-Strings-in-C-Programming

It's probably written at the right level for you. Good luck and welcome to stackoverflow!

Upvotes: 2

Related Questions