作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
代码:
#include <stdio.h>
typedef struct person {
int age ;
char name[40];
}person;
void perm ( person * A , person * B ){
person temp ;
temp = *A ;
*A = *B ;
*B = temp ;
}
void main () {
person classroom[6];
int i , j ;
// reading students name and ages
for ( i=0 ; i<6 ; i++ ){
printf("Enter name :");
fgets (classroom[i].name, 40, stdin);
printf("Enter age : ");
scanf("%d",&classroom[i].age);
}
// sorting them
for ( i=0 ; i<6 ; i++ ){
for ( j=0 ; j<6-i ; j++ ){
if ( classroom[j].age > classroom[j+1].age ){
perm (&classroom[j],&classroom[j+1]);
}
}
}
// printing them sorted
printf("\n After sorting accoring to ages :");
for ( i=0 ; i<6 ; i++ ){
printf(" %s \n",classroom[i].name[40]);
}
// finished
getchar();
getchar();
}
该程序应该:
最佳答案
我快速检查了一下,发现该代码中至少有 3 个主要错误:
1) 当你查找学生姓名时,你会遇到麻烦,因为 scanf 中没有正确处理 '\n',要正确处理它,你需要使用 '\n',例如你可以添加getc() 直接在 scanf 之后,就像我在下面的代码片段中所做的那样:
for ( i=0 ; i<6 ; i++ ){
printf("Enter name :");
fgets (classroom[i].name, 40, stdin);
printf("Enter age : ");
scanf("%d",&classroom[i].age);
/* Add this one will catch the \n for you making the code working better */
getc(stdin); /* <<<<< ADD THIS LINE */
}
2)这里存在缓冲区溢出:
for ( j=0 ; j<6-i ; j++ ){
if ( classroom[j].age > classroom[j+1].age ){
perm (&classroom[j],&classroom[j+1]);
}
}
当 i=0, j=5 =>classroom[j+1]==>classroom[6] 且索引 6 时,它位于边界之外。您需要将循环设置为最多 5
for ( j=0 ; j<5-i ; j++ ){
if ( classroom[j].age > classroom[j+1].age ){
perm (&classroom[j],&classroom[j+1]);
}
}
3) 当您打印结果时,您指向的位置超出了字符串的末尾。此外,您没有指向字符串,但尝试获取为名称保留的空间之外的第一个字符,因为您错过了符号“&”,而不是:
printf(" %s \n",classroom[i].name[40]);
您必须使用以下内容:
printf(" %s \n", &classroom[i].name[0]);
关于c - 制作一个初学者 C 程序来根据年龄读取和排序学生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22120672/
我是一名优秀的程序员,十分优秀!