简体   繁体   中英

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. 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. is there a fix, or alternative from fscanf() , since it can't read 2 string?

This problem is occurring because you put rewind() inside the for loop . Place it before the for loop. 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.

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.

Probably you want to remove the '\\n' from the format string in the scanning part.

After that, as mentioned in the other answer by W.Jack , the positioning of rewind() appears wrong, too. You need to rewind once, before the reading starts. Make the call outside the reading loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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