Read input from a file and output results

Hi all,

I need to write code to read input from a file and then use that input to output results.

My file looks like this:

5 S
2.99 12.45 13.23 21.99 24.59
1 E
34.95
3 E
8.99 12.45 7.58
7 S
5.66 12.35 23.56 40 12.99 16.32 11.23

The name of the input file is books.dat I placed it in the same directory as my code but I get an error:

bookSales2_MyName.cpp: In function `int main()':
bookSales2_MyName.cpp:15: error: `books' was not declared in this scope


My code is far fro mdone and I am having trouble getting anywhere close to my end result which needs to do certain things listed below:

1. Obtain the name of the data file from the user and attempt to open it for reading. If the attempt to open the file fails, the program should report an appropriate error message and quit.
2. Obtain all input for each sale from the data file. The function should return the merchandise total and shipping method for the current sale being processed.
3. Calculate all discounts, fees, taxes, and any other related items for each sale.
4. Display a final summary for each sale.

I need to use functions in my main(). I am far from finished please help!

Thank you,

TECK

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <fstream>
using namespace std;
void ReadFromFile();

int main()
{

  int nameOfFile;
  ifstream fp;

  cout<<"What is the name of the file? ";
  cin>>nameOfFile;

  fp.open(books.dat);

  ReadFromFile();
}

void ReadFromFile()
{
 ifstream fp;
  while(fp.eof() == false)
    {

    }
}
Put the books.dat arg in double quotes. so: "books.dat" not books.dat.

Aceix.
Change int nameOfFile; to std::string nameOfFile;


and then put
fp.open(nameOfFile.c_str());

Pass fp as a parameter to the function:
void ReadFromFile(ifstream &fp)
Last edited on
I am givin the data file called "books.dat" which has the data

5 S
2.99 12.45 13.23 21.99 24.59
1 E
34.95
3 E
8.99 12.45 7.58
7 S
5.66 12.35 23.56 40 12.99 16.32 11.23

how do I read in the number on each line as a price of a books and the character as a shipping method S for standard and E for Expedited.
This need some sort of loop structure. First read the "5 S" part.
Then use the value just read to control a loop.

I'd recommend that eof() is not used, it often leads to logic errors and undetected read errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    int count;
    char letter;
    double number;
    
    while (fp)
    {
        fp >> count >> letter;               // get "5 S";
        
        if (fp)
        {
            for (int i=0; i<count; i++)     // get the list of numbers
            {
                fp >> number;
            }
        }
    }

Topic archived. No new replies allowed.