-1
char *word[128];
fgets(word, 128, stdin);
if(word == "hello")
    printf("You entered hello as your word."); 

So basically I am trying to get user input as a string and then use the following comparison so see if the string the user entered is equal to "hello". however, when compiling this code, it doesn't work. What did I do wrong?

EDIT: So based on feedback so far this is what I have:

char word[128];
fgets(word, 128, stdin);
if(strcmp(word, "Hello") == 0)
     printf("match\n");

However, when I compile and run this program and enter Hello it does not print "match".

10
  • 3
    == is not how string comparisons are done in C. Use strcmp.
    – kaylum
    Commented Feb 10, 2016 at 2:54
  • 5
    How do I properly compare strings in C?
    – kaylum
    Commented Feb 10, 2016 at 2:56
  • If you learn how to hard-code and print strings, you can separate the two functions (getting user input and comparing strings) and tackle them independently.
    – Beta
    Commented Feb 10, 2016 at 2:56
  • Is me needing to use strcmp the only thing that is wrong with the above code? Is the string defined properly and would fgets work in this case with how the string is defined? Commented Feb 10, 2016 at 2:56
  • 1
    char *word[128] should be char word[128]. That plus strcmp should work.
    – kaylum
    Commented Feb 10, 2016 at 2:57

2 Answers 2

0

You need to use strcmp to compare strings.

if(strcmp(word, "Hello") == 0)
  printf("match\n");
0

Use strcmp(char *s1, char *s2) to compare strings. Also change char *wordto char word[].

fgets, as you used it, reads in characters from stdin until it has read new line, 127 characters or EOF (end of file). The new line is part of the string read in word and so the comparison is not equal.

To illustrate, you need to know that a C-style string is an array of characters ended by the special escape character \0. So you are comparing those two strings hello\n\0 and hello\0; note the newline character in the string read from stdin.

You can overwrite the \n at the 6th position with \0 so your strings compare to equal.
A better, general solution is to simply iterate over the characters of the string and replace the first found \n by \0; this could be a good exercise for you maybe.

== does not compare the strings the way you expect it. It merely compares the addresses of the two objects, which in this case are of course different.

Not the answer you're looking for? Browse other questions tagged or ask your own question.