简体   繁体   English

fscanf()仅在读取文件上的struct时才能接受一个字符串,而不是int C

[英]fscanf() only can accept one string when read struct on file, not with int C

I have another Problem, fscanf() only can read one string even, there is 2 in file, so it just repeat it. 我还有另一个问题, fscanf()甚至只能读取一个字符串,文件中有2个,因此只需重复一次即可。 Ex. 例如 In file 在文件中

Name
ID

when I read it. 当我阅读它时。

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");

When writing: 撰写时:

 int i;
   for (i = 1; i < 3; i++) {
        fprintf(test, "%s\n", custid[i].name);
   }

And reading: 并阅读:

for (i = 1; i < 3; i++) {
        rewind(test);
        fscanf(test, "%s\n", custid[i].name);
        printf("%s\n", custid[i].name);
    }

The Result: 结果:

Name
Name

Process returned 0 (0x0)   execution time : 0.007 s
Press any key to continue.

But When I do it with int, you can have 2 different result, which is what I wanted. 但是,当我使用int进行操作时,您可以得到2个不同的结果,这正是我想要的。 is there a fix, or alternative from fscanf() , since it can't read 2 string? 是否有修复程序或fscanf()替代方法,因为它无法读取2个字符串?

This problem is occurring because you put rewind() inside the for loop . 发生此问题是因为您将rewind()放入了for循环中。 Place it before the for loop. 将其放在for循环之前。 Then it will work fine. 然后它将正常工作。

 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);
 }

This is probably, your scanning is failing. 这可能是您的扫描失败。

Moral of the story: Always check the return value of scanf() family for success before trying to use the scanned value. 故事的寓意:在尝试使用扫描的值之前,请始终检查scanf()系列的返回值是否成功。

In your case, 就你而言

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

needs an explicit '\\n' to be present in the input to be match, without that, the matching will fail. 需要在输入中存在一个明确的'\\n'来进行匹配,否则,匹配将失败。

Probably you want to remove the '\\n' from the format string in the scanning part. 可能您想从扫描部分的格式字符串中删除'\\n'

After that, as mentioned in the other answer by W.Jack , the positioning of rewind() appears wrong, too. 之后,如W.Jack另一个答案所述, rewind()的位置也出现错误。 You need to rewind once, before the reading starts. 开始阅读之前,您需要倒带一次。 Make the call outside the reading loop. 在阅读循环外拨打电话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM