0

I have a small problem using gets function and a simple if expression. It has to check whether the input is correct or no, in this case should be: !S

char checkCommand[5];
gets(checkCommand);
if(checkCommand=="!S")....;
else puts("Invalid command!"); 

How come I never end up to get true value for the expression, even if I type !S ? Thanks for all answers!

B1nd0
  • 110
  • 1
  • 8
  • Also note that the gets() function has been removed from the C language since it was deemed broken beyond repair. You should use `fgets()` instead. – Lundin May 06 '14 at 09:44

4 Answers4

4

Because you do not compare strings in C like this: (checkCommand=="!S")

To compare strings, you should use strcmp or strncmp or memcmp functions.

Example: In your case you use it like this:

if (strncmp(checkCommand, "!S", 5) == 0)

To read more about these functions, visit this link and similar.

You should also have noticed a warning "gets is dangerous..." something like this. You should avoid using gets and use fgets instead. The reason is well explained by Chris Jester-Young in his answer.

0xF1
  • 6,046
  • 2
  • 27
  • 50
1

C has no strings; it has character pointers, and == simply compares the pointers. Use strcmp or strcasecmp (if your system has that) to compare strings. Note that strcmp returns 0 when the strings compare equally.

Also, avoid using gets. If a user enters a string longer than 4 characters (in your case), other parts of your memory will start getting scribbled on. Instead, prefer to use fgets, which allows you to specify the size of your input buffer.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • 2
    "C has no strings" shouldn't be stated like that. C has no specific data type for strings, but a string in C is a `0` terminated `char` array. – Jens Gustedt May 06 '14 at 09:45
  • 1
    [pedantic] _"it has character pointers"_ -> it has char arrays and pointers to chars. A `char *` needn't be a string ( `scanf(" %c", &some_char);`) – Elias Van Ootegem May 06 '14 at 10:10
0

You must use strcmp() function to compare two strings in c

 int ret;
 ret=strcmp(checkCommand,"!s");
 if(ret!=0)   
 {
 printf("Invalid Command");
 }
Möbius
  • 17
  • 1
  • 1
  • 9
-2

Replace if(checkCommand=="!S") -> if(!strcmp(checkcommand,"!S"))

Rocoder
  • 1,083
  • 2
  • 15
  • 26