【发布时间】:2017-11-26 12:20:16
【问题描述】:
我正在修改我的基本 C 以准备即将到来的测验,当时我正在编写一个函数来简单地获取字符输入并将其存储到结构中并再次打印出来。编译没有任何问题,但我一直遇到逻辑问题。我该如何解决这个问题?
#include <stdio.h>
struct player
{
char letter;
int age;
double avg;
};
int main()
{
struct player P1;
char name;
int age;
double avg;
printf("Enter age: ");
scanf("%d", &age);
printf("Enter avg: ");
scanf("%lf", &avg);
printf("Enter name: ");
scanf("%s", &name);
P1.letter= name;
P1.avg = avg;
P1.age = age;
printf("\n Age is: %d \n", P1.age);
printf("Avg is: %lf", P1.avg);
printf(" \n Name is: %c \n", P1.letter);
return 0;
}
如果我为 int 输入“1”,输出将是“年龄为:0”
【问题讨论】:
-
scanf("%s", &name);=>scanf("%c", &name); -
scanf("%s", &name);- 你应该read the requirementsof the%sformat specifier.。您没有提供足够的空间来读取名称字符串。 -
好旧的缓冲区溢出!永远不要写入长度未知的 C 字符串。从不。
-
请查看
scanf的返回值 -
使用 fgets 从键盘读取,使用 sscanf 从读取字符串中提取