Search code examples
cstringprintfscanfstdio

scanf and printf not printing right values


What is going on here? The code goes like:

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

int main()
{
    char name[15];
    char name_[15];
    char answ[1];

    printf("What's your name?\n");
    scanf("%s", name);

    strcpy(name_, name);

    printf("Yes / No: ");
    scanf("%s", answ);

    printf("Hello! %s\n", name_);
    printf("You said: %s\n", answ);

    return 0;
}

With input "name" and "yes" the expected output is that it says:

Hello! name

You said: yes

Instead I get:

Hello! es

You said: yes

I also tried adding spaces before %s with no results.

So what exactly am I missing here?


Solution

  • answ can contain only 1 character. So currently, the extra character "es" + '\0' gets written into the memory assigned to name_. So, "es" gets printed.