c++ - 该程序应该创建一个包含结果的输出文件,但文件中没有任何内容

标签 c++ ofstream

我的代码正在创建“output.txt”,但它没有将任何内容输出到文件中。

理想情况下,它应该读取一个文本文件,例如

游戏 2300.00 1000.00

糖果 1500.00 900.00

音乐 1500.00 1000.00

饮料 3000.00 2000.00

XXXXXX

并输出

按收入递减顺序报告-

游戏 1300

饮料 1000

糖果 600

音乐 500

统计:-

摊位数量:4

盈利摊位数:4

所有摊位的总利润:3400

摆摊盈利:音乐甜酒小游戏

#include <iostream>
#include <fstream> // for file streaming

using namespace std;


int main()
{


    ifstream f; // this is a input file object
    f.open("stalls.txt"); // open file with the f object

    ofstream of; // this is a output file object
    of.open("output.txt"); // open file "output.txt" with the of object

    while (loop) {
        f >> tmp.name; // read from the file

        if (tmp.name == "xxxxxx") {
            loop = false;
            continue;
        }

如果有人能告诉我我做错了什么以及为什么我的 output.txt 中没有任何内容,我将不胜感激

最佳答案

在您的输入文件中,您使用大写的“X”来标记文件的结尾,但在您的代码中,您正在检查小写的“x”。这就是为什么您的代码在输入循环期间遇到运行时错误并且从未真正到达打印输出部分的原因。

解决这个问题,你就会没事的。但我建议您检查 EOF 而不是使用“xxxxxx”来标记 EOF。为此,您无需标记输入文件的末尾,而是像这样编写输入 while:

while (f >> tmp.name) {
  if (tmp.name == "xxxxxx") {
    loop = false;
    continue;
  }

  f >> tmp.income; // read income from the file
  f >> tmp.expenses; // read expenses from the file

  tmp.net = tmp.income - tmp.expenses;
  tprofit_loss += tmp.net;

  Stalls[n] = tmp;

  n++;
}

关于c++ - 该程序应该创建一个包含结果的输出文件,但文件中没有任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56487142/

相关文章:

c++ - ofstream的使用

c++ - 如果不在内存中,表达式和常量存储在哪里?

c++ - C 与 C++ 中的外部函数

c++ - Ofstream,使用变量命名

c++ - vector 迭代器不可取消引用( vector 内 vector )

c++ - 如何查看文件拷贝写入是否成功

c++ - 如何在 Xcode 中引用图像和其他对象以及将它们放置在何处?

python - 如何在 Python 的 struct 中使用 C++ struct

c++17 `filesystem` 不是命名空间名称

C++ ifstream读取2个字符数