[英]fscanf() only can accept one string when read struct on file, not with int C
我还有另一个问题, fscanf()
甚至只能读取一个字符串,文件中有2个,因此只需重复一次即可。 例如 在文件中
Name
ID
当我阅读它时。
struct customer {
int id;
char name[100];
};
struct customer custid[100];
int num_cust = 1;
strcpy(custid[num_cust].name, "Name");
num_cust++;
strcpy(custid[num_cust].name, "ID");
撰写时:
int i;
for (i = 1; i < 3; i++) {
fprintf(test, "%s\n", custid[i].name);
}
并阅读:
for (i = 1; i < 3; i++) {
rewind(test);
fscanf(test, "%s\n", custid[i].name);
printf("%s\n", custid[i].name);
}
结果:
Name
Name
Process returned 0 (0x0) execution time : 0.007 s
Press any key to continue.
但是,当我使用int进行操作时,您可以得到2个不同的结果,这正是我想要的。 是否有修复程序或fscanf()
替代方法,因为它无法读取2个字符串?
发生此问题是因为您将rewind()
放入了for循环中。 将其放在for循环之前。 然后它将正常工作。
int i;
for (i = 0; i < 2; i++) {
fprintf(test, "%s\n", custid[i].name);
}
rewind(test);
for (i = 0; i < 2; i++) {
// rewind(test);
fscanf(test, "%s\n", custid[i].name);
printf("%s\n", custid[i].name);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.