【发布时间】:2015-04-18 16:41:25
【问题描述】:
我正在实现一个程序,该程序从标准输入或文件中读取学生 ID 和姓名,并使它们按姓名排序并按数字排序。有趣的是我不明白为什么但 scanf 不起作用。这是我使用 scanf 时的代码:
int n=0;
while(n<SIZE){
scanf("%d %s\n",&std_array[n].id, std_array[n].name);
n++;
}
for(int i=0; i<SIZE; i++)
printf("%d %s\n",std_array[i].id,std_array[i].name);
这是我的结构:
struct Student {
char *name;
int id;};
当我从文件中读取并打印它们时,输出是:
> 12586546 (null) 0 (null) 0 (null) 0 (null) 0 (null) 0 (null) 0 (null)
> 0 (null) 0 (null) 0 (null)
虽然文件有一些数字和名称,如 21456764 john 45797654 fred 等,但它没有成功读取。
注意:我知道我们像你们建议的那样修复 struct 的方式,但我必须学习使用 char 指针执行此操作的方式...
【问题讨论】:
-
您应该始终测试
scanf的结果项计数
标签: c pointers scanf dynamic-memory-allocation