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

4 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 
1
#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; } 
2

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.

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

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy