Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text from user input using C

Tags:

I am just learning C and making a basic "hello, NAME" program. I have got it working to read the user's input but it is output as numbers and not what they enter?

What am I doing wrong?

#include <stdio.h>

int main()
{
    char name[20];

    printf("Hello. What's your name?\n");
    scanf("%d", &name);
    printf("Hi there, %d", name);

    getchar();
    return 0;
}
like image 644
Callum Whyte Avatar asked Feb 27 '14 10:02

Callum Whyte


Video Answer


2 Answers

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
like image 140
Sadique Avatar answered Oct 31 '22 13:10

Sadique


#include <stdio.h>

int main()
{
char name[20];

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

getchar();
return 0;
}
like image 37
MONTYHS Avatar answered Oct 31 '22 11:10

MONTYHS