【问题标题】:My output will not write to a file [closed]我的输出不会写入文件[关闭]
【发布时间】:2016-07-19 00:37:49
【问题描述】:

这是我写的代码:

#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;
}

我期待它会读取文件中的值,然后将每个值立方。在对文件中的每个值进行立方计算后,它将获得这些立方值的总和。但是没有任何内容打印到输出中。

【问题讨论】:

  • 文件创建了吗?您应该检查 fopen() 的结果以验证它是否成功。
  • 您能解释一下您希望如何通过system() 库调用执行两个文件,它们实际上不包含可执行程序,而是包含数字列表?
  • 使用调试器单步调试代码
  • 假设int main(void\n只是一个错字,请检查finfout的值,如果值是NULL,还要检查errno。我怀疑您需要确保输入文件位于正确的目录中。
  • 顺便说一句,您可能希望在每个打印字符串的末尾添加 '\n'。并不是说这似乎与您的问题密切相关。

标签: c++ file


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    相关资源
    最近更新 更多