我正在做作业,需要从输入文件中读取。该程序只是退出错误,但是,我不知道为什么。这是我的代码。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main()
{
FILE *fp = fopen( "input.txt", "r");
FILE *outputF = fopen( "output.txt", "w");
if( !fp || !outputF){
fprintf(stderr, "can't open files for input/output");
exit(EXIT_FAILURE);
}
char line[250];
double factor;
int expo;
while( fscanf( fp, "%f%d", factor, expo) == 1){
if( factor == 0){
fprintf(outputF, "%s\n", "undefined");
}
else{
double total = 1;
for(int i = 0; i < expo; i++){
total = total * factor;
}
fprintf(outputF, "%f", total);
}
}
fclose(fp);
fclose(outputF);
return EXIT_SUCCESS;
}
我认为问题出在“ while”行,但我也使用以下代码进行了尝试,但无法正常工作。输入文件中有一个doulbe和一个用空格分隔的整数。即“ 2.33 3”
while(fscanf(fp, "%s", line) == 1){
char *token;
token = strtok(line, " ");
float factor;
sscanf(token, "%f", &factor);
token = strtok(NULL, "\n");
int expo;
sscanf(token, "%d", &expo);
最佳答案
第一个问题while (fscanf( fp, "%f%d", factor, expo) == 1)
必须是
while (fscanf(fp, "%f%d", &factor, &expo) == 2)
阅读
fscanf()
的手册。它不返回真值,而是返回字符串中匹配的说明符数。第二个问题,由于错误的
scanf()
格式说明符导致的不确定行为,对于double
,您需要"%lf"
而不是"%f"
。第三个问题,必须传递要读取的值的地址,以允许
scanf()
将结果存储在这些变量中,这就是&
在上面固定的fscanf()
中所做的事情。注意:您的编译器应警告这些错误中的两个,错误的格式说明符,并且不对这些特定说明符使用运算符的
&
地址。有两个选项,您可以忽略这些警告,或者在关闭警告的情况下进行编译。这些可能的原因中的第一个确实很糟糕,请不要忽略警告。第二,阅读您的编译器的文档并启用尽可能多的诊断程序,以避免愚蠢的错误。关于c - 读取文件中的 token 时遇到麻烦,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35400623/