c++ - 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
通过整个文本文件。任何帮助都会很棒。
解决方案
我希望您没有看到任何输出,因为您的循环永远不会停止并且您的文件永远不会关闭。如果您希望输出立即出现在文件中,您应该使用或刷新文件,例如。std::flush
std::endl
f << total << "\n" << total << " " << flush;
出于效率原因,文件输出被缓冲,这意味着文件输出首先写入缓冲区,它不会立即出现在文件中。刷新是获取缓冲区并将其立即写入文件的过程。
推荐阅读
- php - html 电子邮件中的表情符号呈现不正确并隐藏在预览文本中
- python - Python:使用滑块根据单元格值更改单元格的颜色
- wordpress - Ninja 表单 - 表单和字段 ID 在前端附加 _1
- c# - 使用 httpclient 对 elasticsearch 执行查询搜索
- spring - r2dbc-oracle 的 LDAP URI 应该如何?
- powerapps - PowerApp:[编辑]/[新建]代码=确定,[编辑]代码然后在 Excel 文件上创建 [新建] 记录(帮助)
- html - css grid 使一个单元格始终是最大的
- r - 更改 R 中森林图中 Axis 刻度和 Xlab 的字体大小
- javascript - Three.js:缩放对象的边界球体
- java - SpringBoot - 为什么@Cacheable 在它的方法有一个对象作为参数时不起作用?