我的输出不会写入文件

时间:2016-07-19 00:37:49

标签: c++ file

这是我写的代码:

#include <stdio.h>
#include<stdlib.h>
int main(void)
{
    float x;//the data value
    float sum=0.0;//the running total of the values readd
    int n=0;//the number of data values read
    float cube;

  FILE* fin = fopen("sumcubes.in", "r"); /* open for reading */
FILE* fout=fopen("sumcubes.c","w");

while(1){
    fscanf(fin,"%f",&x);
    if(feof(fin))break;
    n++;
    cube=x*x*x;
    sum=sum+cube;

}

fprintf(fout,"There are %d values in the file:",n);
fprintf(fout,"The sum of cubes of these values is:%f",sum);
fclose(fin);
fclose(fout);
system("sumcubes.in");
system("sumcubes.c");
system("pause");
return 0;
}

我原以为它会读取文件中的值,然后将每个值立方体化。在对文件中的每个值进行Cubing之后,它将获得这些多维数据集值的总和。但是没有打印到输出中。

1 个答案:

答案 0 :(得分:2)

当我运行你的代码时(在Ken Y-N修正了错字之后),它工作正常,除了生成的三个system()调用&#34;命令未找到&#34;错误消息。文件sumcubes.c包含了预期的结果,但为什么你会给该文件一个.c扩展名让我困惑。当您运行可执行文件时,文件sumcubes.in可能不在您当前的目录中?当我尝试这个时,我遇到了分段错误,但由于你没有检查fopen()的结果,如果输入文件不存在(或者不在你当前的目录中),任何事情都可能发生。