Search code examples
ciostring-comparison

How to print different strings depending on the input?


I want one message to appear if the name Emily or Jack is entered and a different message for another input.

My code:

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

int main()
{
    char name;
    
    printf("What is your name?");
        
    gets(name);
    
    if ((strcmp(name,"Emily") == 0) || (strcmp(name,"Jack") == 0))
    {
        printf("Hello %s\n", name); 
    } else 
    {
        printf("Welcome Stranger!\n");
    }
    
    return 0;
}

This code will compile but won't output anything.


Solution

  • The first problem is that name can store exactly one char, to store a string of characters you'll need a char array.

    The second problem, not causing the faulty behavior but equaly important, is the use of gets. This function was deprecated in C99 and removed from the international standard with C11, and for good reason, it's very dangerous as it can easily overflow the destination buffer, it has no control over the length of the input stream. fgets is regularly used instead.

    char name[256]; //array store the name
    
    //...
    
    fgets(name, sizeof name, stdin); //safe, can't overflow the buffer, input size is limited
    name[strcspn(name, "\n")] = '\0'; //fgets parses the newline character, it must be removed
    
    //...