【发布时间】:2018-03-08 22:57:41
【问题描述】:
当 for 循环第一次运行时,程序等待用户输入。但是在第一次之后似乎跳过了两条 scanf 行。
我已经注释掉了杂项代码:
#include <stdio.h>
int n = 0;
struct student {
int age;
char name[20];
};
void enterStudents() {
printf("How many students do you want to enter? \n");
scanf("%d", &n);
struct student list[n];
for(int i=0; i<n; i++){
printf("Enter student number %d's age: ", i+1);
scanf("%d", &list[i].age);
printf("Enter student number %d's name: ", i+1);
scanf(" %c", list[i].name);
}
listSort(list);
}
/**int listSort(struct student list[n]) {
char tempName[20];
int tempAge;
for(int i=0; i<n-1; i++){
if(list[n].age < list[n+1].age) {
tempAge = list[n].age;
strcpy(tempName, list[n].name);
list[n].age = list[n+1].age;
strcpy(list[n].name, list[n+1].name);
list[n+1].age = tempAge;
strcpy(list[n+1].name, tempName);
}
}
}**/
int main() {
enterStudents();
}
【问题讨论】:
-
你的意思可能是
scanf(" %19s", list[i].name);读取学生的名字 -
@Pablo 哇,它成功了!谢谢
-
@Pablo
scanf(" %19s", list[i].name);中的前导空格是不必要的 - 但并不令人反感。 -
@chux 我知道,我已经从 OP 复制和粘贴并将
%c更改为%19s却没有意识到有一个空白空间。当我意识到这一点时,已经过了 5 分钟,我无法再编辑评论了。