[英]Why does this C code always output a smiley face?
#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.
我意识到,如果将%c更改为%s,该程序会正常运行,但是我想知道的是为什么为什么输出的结果是笑脸? Also, if the second %c is replaced with a %s ie
另外,如果第二个%c替换为%s,即
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@".
例如,如果输入为“ Sam”,则输出为“ 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
. 您将错误的参数传递给“%c”说明符,该说明符期望指向单个
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. 相反,您需要使用
"%s"
说明符,并且由于name
是一个数组,因此它自动是指向其第一个元素的指针,因此您不需要操作符的&
地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.