-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".

2 Answers2

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.

Ely
  • 10,860
  • 4
  • 43
  • 64
0

You need to use strcmp to compare strings.

if(strcmp(word, "Hello") == 0)
  printf("match\n");
Umamahesh P
  • 1,224
  • 10
  • 14