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

C++如何实现每次从文件中读取指定数量的float变量?

代码问题汇总

  • 语法缺失:多个语句末尾未加C++要求的分号,包括openFile (output, argv[2])、两个root变量赋值语句、input.close()语句末尾都漏写分号,会直接编译失败。
  • 作用域错误:ofstream output定义在while循环内部,循环外的output.close()无法访问该变量,会触发未定义标识符的编译错误。
  • 输出文件逻辑错误:每次循环都重新打开输出文件,默认覆盖模式会清空上一次写入的内容,最终输出文件仅保留最后一组计算结果,且重复打开关闭文件会带来不必要的性能开销。
  • 输出无分隔符:直接连续输出变量会导致多个数值拼接在一起,后续无法区分各个字段的值。

修正后代码

int main(int argc, char* argv[])
{
    float a, b, c, root1, root2;
    ifstream input;
    ofstream output;
    
    if (openFile(input, argv[1]) && openFile(output, argv[2]))
    {
        while (input >> a >> b >> c)
        { 
            root1 = a + b + c; //for example
            root2 = a - b - c; //for example
            // 用空格分隔各个字段,方便后续读取
            output << a << " " << b << " " << c << " " << root1 << " " << root2 << endl;
        } 
        input.close();
        output.close();
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者Jacob Adams

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:54:02