简体   繁体   English

带整数和字符的fscanf格式

[英]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 1 \\ 4 + 1 \\ 3
2\\5 - 6\\13 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 您还需要仅在checkScan==5时执行printf,否则您不知道要打印什么

  • you also need to increment line only when the input is ok 您还需要仅在输入正常时才增加行数

  • you need to check line is < 100 您需要检查是否小于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 . 您的scanf格式无效。

ope is char type, but in scanf you require ac string (char*). ope是char类型,但是在scanf中,您需要一个ac字符串(char *)。

If you want to read a signle char, you should use %c as format parameter for scanf: 如果要读取符号字符,则应将%c用作scanf的格式参数:

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

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

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