如何在C语言中用fscanf从.dad文件读取1/2并转为0.5
解决fscanf读取分数时只获取整数部分的问题
问题原因
你当前用%lf格式符读取文件内容时,fscanf会在遇到非数字字符(这里是/)时停止解析,所以只会读取到1,最终变量x的值是1.0,而非期望的0.5。
解决方案
要正确解析1/2这种分数格式,需要让fscanf同时读取分子和分母,再计算两者的商。以下是两种可行的实现方式:
方法1:直接匹配分数格式
使用%lf/%lf格式字符串,一次性读取分子、跳过/、读取分母,再计算结果:
#include <stdio.h> int main(void){ FILE *file; file = fopen("test.dad", "r"); if (file == NULL){ printf("Error opening .dad file.\n"); return 1; } double numerator, denominator; double x = 0; // 匹配"分子/分母"格式,成功读取2个值才继续执行 if (fscanf(file, "%lf/%lf", &numerator, &denominator) == 2) { if (denominator != 0) { x = numerator / denominator; } else { printf("Error: Denominator cannot be zero.\n"); fclose(file); return 1; } } else { printf("Error: Failed to parse fraction from file.\n"); fclose(file); return 1; } fclose(file); printf("%lf\n", x); return 0; }
运行这段代码,输出会是0.500000,符合预期。如果文件中的分数带有空格(比如1 / 2),只需把格式字符串改成%lf /%lf即可兼容。
方法2:先读取字符串再解析
如果分数格式不固定(比如可能有空格、换行等),可以先把整行内容读取到字符串缓冲区,再用sscanf解析:
#include <stdio.h> #include <string.h> int main(void){ FILE *file; file = fopen("test.dad", "r"); if (file == NULL){ printf("Error opening .dad file.\n"); return 1; } char buffer[100]; double numerator, denominator; double x = 0; // 读取整行内容到缓冲区 if (fgets(buffer, sizeof(buffer), file) != NULL) { // 从缓冲区解析分子和分母 if (sscanf(buffer, "%lf/%lf", &numerator, &denominator) == 2) { if (denominator != 0) { x = numerator / denominator; } else { printf("Error: Denominator cannot be zero.\n"); fclose(file); return 1; } } else { printf("Error: Failed to parse fraction.\n"); fclose(file); return 1; } } else { printf("Error: Failed to read file content.\n"); fclose(file); return 1; } fclose(file); printf("%lf\n", x); return 0; }
这种方法更灵活,能处理文件中分数前后的空白字符。
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

