【发布时间】:2014-01-15 13:07:20
【问题描述】:
下面的代码与scanf() 完美运行,但我想输入字符和空格。我尝试过gets() 和fgets()(在下面评论),但它不起作用(它跳到循环中的下一次迭代并在fgets() 使用的名称输入的输出期间显示空白(NULL))。知道怎么做吗?
PS:我已经用示例程序尝试了fputs(),它工作正常。但是我在使用结构指针时有点困惑。
#include <stdio.h>
#include <stdlib.h>
struct details {
uint Id;
char Name[20];
};
int main() {
int tot, i;
struct details *info;
printf("Enter no. of details to be stored = ");
scanf("%d", &tot);
info = (struct details *)malloc(tot*sizeof(struct details));
for(i=0; i<tot; i++) {
printf("%d)Id = ", i+1);
scanf("%d", &info->Id);
printf("%d)Name = ", i+1);
fgets(info->Name, 20, stdin); //How to make fgets() work??
//scanf("%s", &info->Name); //works fine with scanf()
info++;
}
for(i=0; i<tot; i++) {
--info;
}
printf("\nDisplaying details:\n");
for(i=0; i<tot; i++) {
printf("%d)Id = %d\n%d)Name = %s\n", i+1, info->Id, i+1, info->Name);
info++;
}
return 0;
}
输出:
[xyz@xyz:Temp] $ ./fgets_Struct
Enter no. of details to be stored = 2
1)Id = 111
1)Name = 2)Id = 222
2)Name =
Displaying details:
1)Id = 111
1)Name =
2)Id = 222
2)Name =
[xyz@xyz:Temp] $
【问题讨论】:
-
当你说它不起作用时,你是什么意思?你的循环有一个问题,你应该使用一个临时变量来保存存储在变量信息中的原始地址。
-
不工作?请更具体一点。它是否返回一些垃圾数据,或者它是哪种“不工作”?
-
另见这个关于使用 fgets() 和 sscanf() 的 stackoverflow stackoverflow.com/questions/19363951/…
-
@RichardChambers 我已经更新了问题,请看一下
-
@V-X 我已经更新了问题,请看一下。