首页 > 解决方案 > Ofstream 似乎没有输出

问题描述

所以我正在尝试为计算器创建一个日志,这样我就可以回去检查以确保所有输入的数字都正确输入。这是代码。

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    ofstream f;
    f.open("pumpout.txt");

    float number = 0;
    float total = 0;
    char operand;
    bool running = true;

    cin >> total;
    f << total << " ";
    cin >> operand;
    f << operand << " ";
    cin >> number;
    f << number << " = ";

    while (running = true) {

        if (operand == '/') {
            total = total / number;
            cout << total << endl;
            f << total << "\n" << total << " ";
            cin >> operand;
        }
        else if (operand == '*') {
            total = total * number;
            cout << total << endl;
            f << total << "\n" << total << " ";
            cin >> operand;
        }
        else if (operand == '+') {
            total = total + number;
            cout << total << endl;
            f << total << "\n" << total << " ";
            cin >> operand;
        }
        else if (operand == '-') {
            total = total - number;
            cout << total << endl;
            f << total << "\n" << total << " ";
            cin >> operand;
        } 
        f << operand << " ";
        cin >> number;
        f << number << " = ";
    }
}

所以它会按照我想要的方式添加和执行所有操作,但它不会转到文本文件。格式应为:

total operand # = total

通过整个文本文件。任何帮助都会很棒。

标签: c++fstreamofstream

解决方案


我希望您没有看到任何输出,因为您的循环永远不会停止并且您的文件永远不会关闭。如果您希望输出立即出现在文件中,您应该使用或刷新文件,例如。std::flushstd::endlf << total << "\n" << total << " " << flush;

出于效率原因,文件输出被缓冲,这意味着文件输出首先写入缓冲区,它不会立即出现在文件中。刷新是获取缓冲区并将其立即写入文件的过程。


推荐阅读