Callum Whyte
Callum Whyte

Reputation: 2429

Get text from user input using C

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;
}

Upvotes: 23

Views: 128546

Answers (4)

MONTYHS
MONTYHS

Reputation: 924

#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;
}

Upvotes: 7

user3359601
user3359601

Reputation: 17

change your code to:

int main()
{
    char name[20];

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

    getchar();
    getch();                  //To wait until you press a key and then exit the application
    return 0;
}

This is because, %d is used for integer datatypes and %s and %c are used for string and character types

Upvotes: -2

Rahul
Rahul

Reputation: 3509

When we take the input as a string from the user, %s is used. And the address is given where the string to be stored.

scanf("%s",name);
printf("%s",name);

hear name give you the base address of array name. The value of name and &name would be equal but there is very much difference between them. name gives the base address of array and if you will calculate name+1 it will give you next address i.e. address of name[1] but if you perform &name+1, it will be next address to the whole array.

Upvotes: 1

Sadique
Sadique

Reputation: 22821

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

Upvotes: 37

Related Questions