【发布时间】:2022-06-14 01:13:11
【问题描述】:
我必须用 C 编写一个作业,我们必须在其中定义一个结构并对其执行一些操作。这是我写的代码:
#include <stdio.h>
struct student {
char name[100];
int roll_no;
int chem, phy, math, total;
};
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
struct student s[n];
for(int i = 0; i < n; i++) {
printf("Enter the name of the student: ");
gets(s[i].name);
printf("Enter the roll number of the student: ");
scanf("%d", &s[i].roll_no);
printf("Enter the marks of phy, chem and maths: ");
scanf("%d %d %d", &s[i].phy, &s[i].chem, &s[i].math);
s[i].total = s[i].phy + s[i].chem + s[i].math;
}
printf("\n\nMerit List\n");
printf("Rank \tName \tRollno \tPhy \tChem \tMaths \tTotal\n");
for(int i = 0; i < n; i++) {
printf("%d \t%s \t%d \t%d \t%d \t%d \t%d\n", i + 1, s[i].name, s[i].roll_no, s[i].phy, s[i].chem, s[i].math, s[i].total);
}
return 0;
}
当我编译和运行这个函数时,我无法正确输入值。我什至没有正确看到输入消息,因为这是输入消息。
Enter the number of students: 2
Enter the name of the student: Enter the roll number of the student: skdjk 3
Enter the marks of phy, chem and maths: Enter the name of the student: Enter the roll number of the student: 3 4 6 dskj 2
Enter the marks of phy, chem and maths:
这不是我所期望的。输出也很奇怪,因为我得到了这个:
Merit List
Rank Name Rollno Phy Chem Maths Total
1 32764 32700 1416183288 32768 1416248756
2 skdjk 3 1 3 3 4 6 -1028599268 -1028599258
当我使用 scanf 输入字符串时,问题正在解决。为什么gets(甚至fgets)会导致这些问题?如何解决?
【问题讨论】:
-
您是否阅读了
gets的手册页?您是否看到“从不使用gets()”和“改为使用fgets”的部分? -
立即停止使用
gets()。这是一个危险的功能,因为您无法指定缓冲区大小,并且它已从语言中删除。请改用fgets()。
标签: c string struct fgets gets