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

The program is supposed to create a output file with results but there is nothing in the file

本文关键字:文件 程序 输出 任何内 结果 一个 创建      更新时间:2023-10-16

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

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

游戏 2300.00 1000.00

糖果 1500.00 900.00

音乐 1500.00 1000.00

饮料 3000.00

2000.00

三十三

和输出

按收入降序报告 -

游戏 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;
        }

如果有人能告诉我我做错了什么以及为什么我的输出中没有任何内容.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++;
}

问题是行Stalls[n] = tmp。当n达到 100 时,程序正在中断,Stalls只能从 0 到 99。所以你需要一个条件来打破循环。类似的东西

if(n >= 100){
    break;
}

同样作为Faisal Rahman Avash,您正在检查小写的x而不是大写的X,这是n将超出界限的主要原因。