Get text from user input using C

You use the wrong format specifier %d– you should use %s. Better still use fgets – scanf is not buffer safe.

Go through the documentations it should not be that difficult:

scanf and fgets

Sample code:

#include <stdio.h>

int main(void) 
{
    char name[20];
    printf("Hello. What's your name?\n");
    //scanf("%s", &name);  - deprecated
    fgets(name,20,stdin);
    printf("Hi there, %s", name);
    return 0;
}

Input:

The Name is Stackoverflow 

Output:

Hello. What's your name?
Hi there, The Name is Stackov

Leave a Comment