gpt4 book ai didi

c - scanf 不起作用

转载 作者:行者123 更新时间:2023-11-30 18:39:29 25 4
gpt4 key购买 nike

我正在实现一个程序,该程序从标准输入或文件中读取学生 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 等,但它没有成功读取。

注意:我知道我们像你们建议的那样修复结构的方法,但我必须学习使用 char 指针来执行此操作的方法...

最佳答案

执行此操作时:

struct Student {
char *name; // This does not allocate memory
int id;};

这里,name是一个指针,没有分配内存,表现得像一个未初始化的文字字符串

尝试修改它会产生未定义的行为

替换为:

struct Student {
char name[50];
int id;};

struct Student {
char name[] = "Initial value gives maximum length. Do not write more!";
int id;};

关于c - scanf 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29720037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com