Anna
Anna

Reputation: 3

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

My code is creating "output.txt" but it doesn't output anything into the file.

Ideally, it should read a text file such as

Games 2300.00 1000.00

Sweets 1500.00 900.00

Music 1500.00 1000.00

Drinks 3000.00 2000.00

XXXXXX

and output

Report in decreasing order of the income -

Games 1300

Drinks 1000

Sweets 600

Music 500

Stats: -

Number of stalls: 4

Number of stalls which made the profit: 4

Total profit from all the stalls: 3400

Stalls with profits: Music Sweets Drinks Games

#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;
        }

If anyone can tell me what I'm doing wrong and why there is nothing in my output.txt, I'd appreciate it

Upvotes: 0

Views: 150

Answers (2)

Zachary Liu
Zachary Liu

Reputation: 75

The problem is the line Stalls[n] = tmp. The program is breaking when n hit 100, and Stalls can only go from 0 to 99. So you need a condition to break the loop. Something like

if(n >= 100){
    break;
}

And also as Faisal Rahman Avash, you are checking for lower case x instead of upper case X, which is the main reason why n will go out of bound.

Upvotes: 0

Faisal Rahman Avash
Faisal Rahman Avash

Reputation: 1256

In your input file, you are using capital 'X' to mark the end of the file but in your code you are checking for small 'x'. That's why your code is running into a runtime error during the input loop and never actually getting to the part of printing output.

Fix that and you'll be fine. But I'd suggest you check for EOF rather than using "xxxxxx" to mark the EOF. To do that, you put nothing to mark the end of your input file and write the input while like this:

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++;
}

Upvotes: 2

Related Questions