#include <stdio.h>
#include <stdlib.h>
//A simple program that asks for the user's name and prints it back out.
int main()
{
char name[15];
printf("What is your name? ");
scanf("%c",&name);
printf("Name: %c",name);
}
Not matter what the input is, a smiley face is always the output. I realize that if I change the %c to a %s, the program would run just fine but what I'm wondering is why, out of all things, a smiley face is the output. Also, if the second %c is replaced with a %s ie
char name[15];
printf("What is your name? ");
scanf("%c",&name);
printf("Name: %s",name);
then an @ symbol is printed after the 1st character of the input. For example, if the input is "Sam", then the output would be "S@". Any ideas as to why this happens?
It's undefined behavior, try
scanf("%14s", name);
You pass the wrong parameter to the "%c" specifier which expects a pointer to a single char
. Instead you need the "%s"
specifier and since name
is an array it's automatically a pointer to it's first element so you don't need the &
address of operator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.