简体   繁体   中英

Trouble reading an integer with fscanf

I've been struggling for more than a day trying to figure out what's wrong with this piece of code,printf is always printing 0 on my screen.

#include <stdio.h>
#include <ctype.h>

int main()
{
int one=0,two=0;
FILE *arq;
arq = fopen ("testando.txt","w+");
fprintf(arq,"1,2,3\n");
fscanf(arq,"%d%d",&one,&two);
printf("%d %d\n",one,two);

return 0;

}

  1. Add commas in fscanf(arq,"%d%d",&one,&two);
  2. Reopen file with r flag - to read it
  3. Don't forget to close files ;)
  4. Opt. you can use return value of fscanf to check how much properties are filled

This works fine:

#include <stdio.h>
#include <ctype.h>

int main()
{
    int one=0,two=0;
    FILE *arq;
    arq = fopen ("testando.txt","w+");
    fprintf(arq,"1,2,3\n");
    fclose(arq);

    arq = fopen("testando.txt","r");
    int r = fscanf(arq,"%d,%d",&one,&two);
    fclose(arq);
    printf("%d %d %d\n",r, one,two);

    return 0;
}

Output:

2 1 2

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