You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言的fscanf从格式化文件中提取指定算术运算符?

用fscanf提取代码行中的运算符

问题需求

需要从输入文件的特定代码行(C = (A[i] OP B[i]) + C) << 3;中提取运算符(+、-、*、/),原实现代码和输入文件内容如下:

原实现代码

FILE *file = fopen("project2Input.txt", "r");
if (file == NULL) {
    perror("Error opening file");
    return 1;
}
int k, N;
char op[3];
fscanf(file, "long myFunction(long A[], long B[], int k, int N) {");
fscanf(file, "long C;");
fscanf(file, "for (int i = %d; i < %d; i++){", &k, &N);
fscanf(file, "(C = (A[i] %2[-+*/] B[i]) + C) << 3;", op);
op[2] = '\0';
fscanf(file, " } return C;}");
fclose(file);
printf("op: %s\n", op);

输入文件(project2Input.txt)内容

long myFunction(long A[], long B[], int k, int N) {
    long C;
    for (int i = k; i < N; i++){
        (C = (A[i] - B[i]) + C) << 3;
    }
    return C;
}

问题分析与修正

原代码的核心问题在于fscanf的格式串匹配错误:

  • %2[-+*/]写法不符合fscanf格式规则,且运算符为单个字符,无需读取2个长度;
  • 格式串未匹配代码行中A[i]与运算符、运算符与B[i]之间的空格。

修正后的代码

FILE *file = fopen("project2Input.txt", "r");
if (file == NULL) {
    perror("Error opening file");
    return 1;
}
int k, N;
char op; // 运算符是单个字符,直接用char类型即可
// 匹配函数定义行,fscanf自动跳过空白(换行、空格等)
fscanf(file, "long myFunction(long A[], long B[], int k, int N) {");
// 匹配变量定义行
fscanf(file, "long C;");
// 匹配for循环头,提取k和N的值
fscanf(file, "for (int i = %d; i < %d; i++){", &k, &N);
// 关键:匹配目标行,用%c读取运算符,同时匹配前后空格
fscanf(file, "(C = (A[i] %c B[i]) + C) << 3;", &op);
// 匹配剩余代码行
fscanf(file, " } return C;}");
fclose(file);
printf("op: %c\n", op); // 输出单个字符

关键修改说明

  1. 将char op[3];改为char op;:运算符为单个字符,无需数组存储,简化逻辑;
  2. 调整目标行的fscanf格式串:"(C = (A[i] %c B[i]) + C) << 3;",%c读取单个运算符,格式串中的空格会匹配输入中的任意空白;
  3. 输出时用%c格式符打印运算符,避免数组处理的冗余。

测试结果

运行修正后的代码,会正确输出输入文件中的运算符-。

内容的提问来源于stack exchange,提问作者Zayed Aldhaheri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 22:12:25