Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在文件上读取struct时,fscanf()只能接受一个字符串,而不能使用int C_C_File Io_Scanf - Fatal编程技术网

在文件上读取struct时,fscanf()只能接受一个字符串,而不能使用int C

在文件上读取struct时,fscanf()只能接受一个字符串,而不能使用int C,c,file-io,scanf,C,File Io,Scanf,我还有一个问题,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].n

我还有一个问题,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);
   }
但是当我用int来做的时候,你可以得到两个不同的结果,这就是我想要的。
由于fscanf无法读取2个字符串,是否有修复或替代方案?

这可能是因为您的扫描失败了

故事的寓意:在尝试使用扫描值之前,请始终检查scanf family的返回值是否成功

就你而言

  fscanf(test, "%s\n", custid[i].name);

需要在要匹配的输入中显示“\n”,否则,匹配将失败

可能要从扫描部分的格式字符串中删除“\n”


之后,如中所述,倒带的位置也出现错误。在开始阅读之前,你需要倒带一次。在读取循环外进行调用。

发生此问题的原因是您将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);
 }

从fscanftest删除%s\n后,custid[i].name;。结果仍然存在,是否有另一种来自fscanfYes的替代方案。getline在文件中逐行迭代更好。需要在要匹配的输入中显示“\n”,否则,匹配将失败。->否。格式中的“\n”不会失败fscanf。它匹配测试中的0个或多个空格。这里不需要它,但也不会导致故障。永远不要使用我们*扫描%s,最好使用FGET
  fscanf(test, "%s\n", custid[i].name);
 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);
 }