-1

I can't get the if statement to print out the "Hey ! Another James \n" line.

Why is this not working, it looks simple enough, lol what am I missing?

I want the message to print if I call myself James.

Thanks

# include <stdio.h>
# include <string.h>


int main (int argc, char** argv)
{
    char first_name[30];
    printf(" Please enter your first name : ");
    fgets(first_name, 30 , stdin);

    if (strcmp(first_name, "James") == 0)
        printf("Hey ! Another James \n");
    else
        printf("Goodbye!\n");
}
Roy Avidan
  • 769
  • 8
  • 25

3 Answers3

2

When you use fgets with the size parameter 30, if the input is less than 29 characters, the '\n' will also enter your string. You just need to add a simple code to remove the '\n' if it exists.

Add this line after fgets:

first_name[strcspn(first_name, "\n")] = 0;
Roy Avidan
  • 769
  • 8
  • 25
0

Your fgets() call also reads the newline character on hitting return. You need to post-process the string to eliminate this character.

// Remove the newline
int length = strlen(first_name);
if(length && first_name[length-1] == '\n') {
    first_name[length-1] = '\0';
}
SirBob
  • 33
  • 1
  • 7
0

after looking at the code, the problem is caused by the fgets. Instead when I used gets, the program ran :

# include <stdio.h>
# include <string.h>

void main ()
{
 char first_name [30];
 printf (" Please enter your first name : ") ;
 gets(first_name) ;

 if ( strcmp (first_name, "James")enter code here == 0)
 printf ("Hey ! Another James \n") ;
  else
   printf ("Goodbye!\n") ;
}