简体   繁体   中英

fscanf format with integers and characters

I have to read a file and get the fractions (numerators, denominators and the math sign)
Here is the input file:

1\\4 + 1\\3
2\\5 - 6\\13

Part of my code:

int numer1[100], numer2[100], denom1[100], denom2[100];
char ope[100];
do{
    checkScan = fscanf(fin, "%d %d %s %d %d", &numer1[line], &denom1[line], &ope[line], &numer2[line], &denom2[line]);
    printf("%d %d %s %d %d\n", numer1[line], denom1[line], ope[line], numer2[line], denom2[line]);
    if(checkScan==EOF){
        printf("End of file\n");
        break;
    }
    if(checkScan!=5){
        printf("Not enough data or invalid data\n");
    }
    line++;
}while(1);

replace

checkScan = fscanf(fin, "%d %d %s %d %d", &numer1[line], &denom1[line], &ope[line], &numer2[line], &denom2[line]);

by

checkScan = fscanf(fin, "%d\\%d %c %d\\%d", &numer1[line], &denom1[line], &ope[line], &numer2[line], &denom2[line]);

additional remarks :

  • you also need to do the printf only when checkScan==5 else you do not know what you print

  • you also need to increment line only when the input is ok

  • you need to check line is < 100

  • if the input string doesn't follow the pattern you will loop indefinitely. I encourage you to first read the line then to parse it.

Cumulating all my remarks :

char readLine[100];
int numer1[100], numer2[100], denom1[100], denom2[100];
char ope[100];

while (fgets(readLine, sizeof(readLine), fin)) {
  int checkScan = sscanf(readLine, "%d\\%d %c %d\\%d", &numer1[line], &denom1[line], &ope[line], &numer2[line], &denom2[line]);

  if(checkScan!=5){
    printf("Not enough data or invalid data\n");
  }
  else {
    printf("%d %d %c %d %d\n", numer1[line], denom1[line], ope[line], numer2[line], denom2[line]);
    if (++line == 100)
      break;
  }
}

note : it is strange to use \\ rather than / for a fraction

You have invalid format in scanf .

ope is char type, but in scanf you require ac string (char*).

If you want to read a signle char, you should use %c as format parameter for scanf:

checkScan = fscanf(fin, "%d %d %c %d %d", &numer1[line], &denom1[line], &ope[line], &numer2[line], &denom2[line]);

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