Having trouble obtaining input from file

This is a discussion on Having trouble obtaining input from file within the C++ Programming forums, part of the General Programming Boards category; I am a beginner student in desperate need of help writing a program. Recently, we have learned about functions, loops ...

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    12

    Having trouble obtaining input from file

    I am a beginner student in desperate need of help writing a program. Recently, we have learned about functions, loops and reading from data files. My assignment is to write a program (Book Sale Calculator) that accepts all input from an external data file and displays a summary for each book sale. The program needs to open the external data file and continue to read in data until the end of the file is reached. No sentinel value can be used to signal termination, and I cannot count the number of items in the file or use a count controlled loop to obtain the data. The data file is stored so that the number of books in each sale and the single character code for shipping (S = Standard which is 4.99 and E for Expedited is 12.99) representing the shipping method is on one line, and the prices for all of the books are on the second line. I need to create four functions for the following:
    (1) Obtain the name of the data file and attempts to open it for readying
    (2) Obtain all input for each sale from the data file. This function should also return the merchandise subtotal and shipping method
    (3) Calculate all taxes and discounts
    (4) Display a final total

    The sales tax is .05%

    Discounts are as follows:
    * If the subtotal is < $50, there is no discount
    * If the subtotal is between $50-$100, the discount is 10%
    & If the subtotal is above $100, the discount is 15%

    Additionally, no global variables can be used and all information must be shared between functions via parameters and return values. My main function should consist of variable declarations, function calls, and a control loop for reading each sale from the file can be there.

    The external data file consists of the following format:
    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

    A sample output of the program:
    The summary for order #1 is as follows:
    Subtotal: 75.25
    Tax: 3.76
    Discount: 7.53
    Shipping: 4.99
    Total: 76.48

    The summary for order #2 is as follows:
    Subtotal: 34.95
    Tax: 1.75
    Discount: 0.00
    Shipping: 12.99
    Total:49.69

    The summary for order #3 is as follows:
    Subtotal: 29.02
    Tax: 1.45
    Discount: 0.00
    Shipping: 12.99
    Total: 43.46

    The summary for order #4 is as follows:
    Subtotal: 122.11
    Tax: 6.11
    Discount: 18.32
    Shipping: 4.99
    Total: 114.89

    Thanks for shopping with us. Come again!

    I have provided the source code that I have come up with so far but am at a complete loss. I really don't have any idea as to how to write this program and would GREATLY appreciate ANY assistance!!

    Code:
    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    #include <iomanip>
    using namespace std;
    
    //This function displays a brief overview explaining the program to the user
    void programOverview()
    {
      cout << "This program will read input from an external file" << endl;
      cout << "and calculate the total amount of money for books sales" << endl;
      cout << "at an online store." << endl;
    }
    
    //Open the file/report error
    void openFile ()
    {
      ifstream fp;
      fp.open ("books.dat");
      if (!fp)
        cout << "Error opening the file" << endl;
        exit (EXIT_FAILURE);
    }
    
    //This function will obtain all input for each sale from the data file and return merchandise total and shipping method for the sale being processed
    
    void obtainInput()
    {
          ifstream fp;
          int books;
          char shipping_method;
          float price;
          float subtotal;
          float shipping_price;
          for (int i=0; i<=books; i++)
            fp >> books;
            fp >> shipping_method;
            for (int i=0; i <= books; i++)
              {
                fp >> price;
              }
         subtotal+=price[i];
            return subtotal;
    
      if (shipping_method == 'S')
          shipping_price = 4.99;
      else
          shipping_price = 12.99;
    }
    
    //Calculate tax, discount, shipping and total
    
      void calculateOutput()
    {
      float tax;
      tax = subtotal * .05;
      float discount;
      if (subtotal < 50)
        discount = 0.00;
      else if (subtotal >= 50 && subtotal <= 100)
          discount = subtotal * .10;
      else
          discount = subtotal * .15;
    
      float total;
      total = subtotal + tax - discount + shipping_price;
    }
    
    //Display a final summary
      void displaySummary()
    {
      cout << "The summary for the order is as follows:" << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Subtotal:" << subtotal << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Tax:" << tax << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Discount:" << discount << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Shipping:" << shipping_price << endl;
      cout << fixed << showpoint << setprecision(2);
      cout << "Total:" << total << endl;
    }
    
    int main ()
    {
    
      programOverview ();
    
      cout << "Book Sale Calculator" << endl;
      cout << "=======================" << endl;
    
      openFile();
    
      obtainInput();
    
      calculateOutput();
    
      displaySummary();
    
    return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    2,698
    Does this program compile without error/warning messages?

    If not please post the complete error/warning message.

    If it does compile what is the program outputting?

    Jim

  3. #3
    Registered User
    Join Date
    Feb 2011
    Posts
    12
    It does not compile. I am having trouble understanding how to obtain input from the external file, and do not understand ifstream fp, passing by reference and what to put in the parameters.

    The following errors come up when the program is compiled:
    bookSales2_LindsayLewis.cpp: In function `void obtainInput()':
    bookSales2_LindsayLewis.cpp:43: error: name lookup of `i' changed for new ISO `for' scoping
    bookSales2_LindsayLewis.cpp:39: error: using obsolete binding at `i'
    bookSales2_LindsayLewis.cpp:43: error: invalid types `float[int]' for array subscript
    bookSales2_LindsayLewis.cpp:44: error: return-statement with a value, in function returning 'void'
    bookSales2_LindsayLewis.cpp: In function `void calculateOutput()':
    bookSales2_LindsayLewis.cpp:57: error: `subtotal' was not declared in this scope
    bookSales2_LindsayLewis.cpp:68: error: `shipping_price' was not declared in this scope
    bookSales2_LindsayLewis.cpp: In function `void displaySummary()':
    bookSales2_LindsayLewis.cpp:76: error: `subtotal' was not declared in this scope
    bookSales2_LindsayLewis.cpp:78: error: `tax' was not declared in this scope
    bookSales2_LindsayLewis.cpp:80: error: `discount' was not declared in this scope
    bookSales2_LindsayLewis.cpp:82: error: `shipping_price' was not declared in this scope
    bookSales2_LindsayLewis.cpp:84: error: `total' was not declared in this scope
    >

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    2,698
    Ok lets start looking at and fixing your error messages the first one:
    bookSales2_LindsayLewis.cpp: In function `void obtainInput()':
    bookSales2_LindsayLewis.cpp:43: error: name lookup of `i' changed for new ISO `for' scoping
    bookSales2_LindsayLewis.cpp:39: error: using obsolete binding at `i'
    bookSales2_LindsayLewis.cpp:43: error: invalid types `float[int]' for array subscript
    bookSales2_LindsayLewis.cpp:44: error: return-statement with a value, in function returning 'void'
    These errors are all contained in the following snippet:
    Code:
            for (int i=0; i <= books; i++)
              {
                fp >> price;
              }
         subtotal+=price[i];
            return subtotal;
    The first error is caused because you define i in the initialization section of your for statement. While this is normally the way you would define this variable you must remember that it will go out of scope at the end of the for loop. Therefore the use of i in the lines following the for statement is incorrect because i no longer exists. To fix this problem you would need to define i before the loop (int i = 0.

    However, in this case it looks to me like you want to total up the prices so the subtotal+=price[i]; line should be inside the loop so you need to move your closing brace to after this line.
    Code:
            for (int i=0; i <= books; i++)
              {
                fp >> price;
                subtotal+=price[i];
              }
    Now the last error is because you can not return anything from a void function. You will probably need to pass some variables into your function by reference so you can return the values to the calling program.

    You may want to study the following links for information on calling functions: Functions I and Functions II .

    Jim

  5. #5
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,638
    bookSales2_LindsayLewis.cpp: In function `void obtainInput()':
    bookSales2_LindsayLewis.cpp:43: error: name lookup of `i' changed for new ISO `for' scoping
    bookSales2_LindsayLewis.cpp:39: error: using obsolete binding at `i'
    So if we look at this:
    Code:
    void obtainInput()
    {
          ifstream fp;
          int books;
          char shipping_method;
          float price;
          float subtotal;
          float shipping_price;
          for (int i=0; i<=books; i++)
            fp >> books;
            fp >> shipping_method;
            for (int i=0; i <= books; i++)
              {
                fp >> price;
              }
         subtotal+=price[i];
            return subtotal;
    
      if (shipping_method == 'S')
          shipping_price = 4.99;
      else
          shipping_price = 12.99;
    }
    Let me insert some braces to show you what this means.
    Code:
    void obtainInput()
    {
          ifstream fp;
          int books;
          char shipping_method;
          float price;
          float subtotal;
          float shipping_price;
          for (int i=0; i<=books; i++) {
            fp >> books;
          }
            fp >> shipping_method;
            for (int i=0; i <= books; i++)
              {
                fp >> price;
              }
         subtotal+=price[i];
            return subtotal;
    
      if (shipping_method == 'S')
          shipping_price = 4.99;
      else
          shipping_price = 12.99;
    }
    So i only exists in between those two braces. And then there is another for loop that only loops one statement. Later, you use the obsolete i ...

    bookSales2_LindsayLewis.cpp:43: error: invalid types `float[int]' for array subscript
    Code:
    float price;
    subtotal+=price[i];
    ... as a subscript for a variable that isn't an array.

    It looks like your i counters should not be used, because you read most of the information related to a receipt into other variables one item at a time. You might loop price five times, but you have to add it to the subtotal, too, each time. The computer isn't going to remember price's value for the ith iteration after the ith iteration automatically. It would take more memory.

    In general, I think your for loops are too small, and you need to brace what they should control. Otherwise, the logic will be different at run time, then what you expect (in addition to compile time errors).
    Code:
    if( fp >> books >> shipping_method ) {
       for ( int i = 0; i < books; i++ ) {
          if( fp >> price ) {
             subtotal += price;
          }
      }
    }
    The branching being there to help you with handling reading errors of course.

    Another frankly disturbing problem is that some functions are listed as returning void but they clearly return things. You really should use return values properly.

    EDIT:

    Also, you have errors related to undefined variables. You can rewrite some functions to define them.
    Code:
      void displaySummary(float tax, float subtotal, float discount, float total)
    {
      cout << "The summary for the order is as follows:" << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Subtotal:" << subtotal << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Tax:" << tax << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Discount:" << discount << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Shipping:" << shipping_price << endl;
      cout << fixed << showpoint << setprecision(2);
      cout << "Total:" << total << endl;
    }
    There should be items you can pass in to complete calculateOutput() as well.
    Last edited by whiteflags; 04-22-2011 at 07:35 PM.

  6. #6
    Registered User
    Join Date
    Feb 2011
    Posts
    12
    Okay, great. I knew that I needed to pass the variables into the other functions. Now I understand where I was wrong and where to make my changes. I am still having the following errors:

    bookSales2_LindsayLewis.cpp: In function `int main()':
    bookSales2_LindsayLewis.cpp:57: error: too few arguments to function `void calcu lateOutput(float, float)'
    bookSales2_LindsayLewis.cpp:101: error: at this point in file
    bookSales2_LindsayLewis.cpp:75: error: too few arguments to function `void displ aySummary(float, float, float, float, float)'
    bookSales2_LindsayLewis.cpp:103: error: at this point in file

    Is it because I need to add parameters into the int main function? And what does too few arguments to function mean?

    My updated code:

    Code:
    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    #include <iomanip>
    using namespace std;
    
    //This function displays a brief overview explaining the program to the user
    void programOverview()
    {
      cout << "This program will read input from an external file" << endl;
      cout << "and calculate the total amount of money for books sales" << endl;
      cout << "at an online store." << endl;
    }
    
    //This function attempts to open the file/report error
    void openFile ()
    {
      ifstream fp;
      fp.open ("books.dat");
      if (!fp)
        cout << "Error opening the file" << endl;
        exit (EXIT_FAILURE);
    }
    
    //This function will obtain all input for each sale from the data file and return merchandise total and shipping method for the sale being processed
    
    void obtainInput()
    {
          ifstream fp;
          int i=0;
          int books;
          char shipping_method;
          float price;
          float subtotal;
          float shipping_price;
    
          if (fp >> books >> shipping_method)
            {
              for (int i=0; i < books; i++)
                {
                  if (fp >> price)
                    {
                      subtotal += price;
                    }
                }
            }
    
      if (shipping_method == 'S')
          shipping_price = 4.99;
      else
          shipping_price = 12.99;
    }
    
    //Calculate tax, discount, shipping and total
    
    void calculateOutput(float subtotal, float shipping_price)
    {
      float tax;
      tax = subtotal * .05;
    
      float discount;
      if (subtotal < 50)
        discount = 0.00;
      else if (subtotal >= 50 && subtotal <= 100)
          discount = subtotal * .10;
      else
          discount = subtotal * .15;
    
      float total;
      total = subtotal + tax - discount + shipping_price;
    }
    //Display a final summary
    void displaySummary(float tax, float subtotal, float discount, float shipping_price, float total)
    {
      cout << "The summary for the order is as follows:" << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Subtotal:" << subtotal << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Tax:" << tax << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Discount:" << discount << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Shipping:" << shipping_price << endl;
      cout << fixed << showpoint << setprecision(2);
      cout << "Total:" << total << endl;
    }
    
    int main ()
    {
    
      programOverview ();
    
      cout << "Book Sale Calculator" << endl;
      cout << "=======================" << endl;
    
      openFile();
    
      obtainInput();
    
      calculateOutput();
    
      displaySummary();
    return 0;
    }

  7. #7
    Registered User
    Join Date
    May 2010
    Posts
    2,698
    You have a function:
    Code:
    void calculateOutput(float subtotal, float shipping_price)
    And you call the program like:
    Code:
    calculateOutput();
    When you call the function you must use the same number and types of variables as your function definition.

    Jim

  8. #8
    Registered User
    Join Date
    Feb 2011
    Posts
    12
    Okay, understood. What does 'expected primary-expression before "float"' mean?

  9. #9
    Registered User
    Join Date
    May 2010
    Posts
    2,698
    It depends on what the rest of the error messages states.

    Jim

  10. #10
    Registered User
    Join Date
    Feb 2011
    Posts
    12
    bookSales2_LindsayLewis.cpp: In function `int main()':
    bookSales2_LindsayLewis.cpp:101: error: expected primary-expression before "float"
    bookSales2_LindsayLewis.cpp:101: error: expected primary-expression before "float"
    bookSales2_LindsayLewis.cpp:103: error: expected primary-expression before "float"
    bookSales2_LindsayLewis.cpp:103: error: expected primary-expression before "float"
    bookSales2_LindsayLewis.cpp:103: error: expected primary-expression before "float"
    bookSales2_LindsayLewis.cpp:103: error: expected primary-expression before "float"
    bookSales2_LindsayLewis.cpp:103: error: expected primary-expression before "float"
    >

    Do I not need to list float before the variables in these lines? And if I don't, it says that the variables that not been defined...

  11. #11
    Registered User
    Join Date
    May 2010
    Posts
    2,698
    Post your current code.

    Jim

  12. #12
    Registered User
    Join Date
    Feb 2011
    Posts
    12
    Code:
    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    #include <iomanip>
    using namespace std;
    
    //This function displays a brief overview explaining the program to the user
    void programOverview()
    {
      cout << "This program will read input from an external file" << endl;
      cout << "and calculate the total amount of money for books sales" << endl;
      cout << "at an online store." << endl;
    }
    
    //This function attempts to open the file/report error
    void openFile ()
    {
      ifstream fp;
      fp.open ("books.dat");
      if (!fp)
        cout << "Error opening the file" << endl;
        exit (EXIT_FAILURE);
    }
    
    //This function will obtain all input for each sale from the data file and return merchandise total and shipping method for the sale being processed
    
    void obtainInput()
    {
          ifstream fp;
          int i=0;
          int books;
          char shipping_method;
          float price;
          float subtotal;
          float shipping_price;
    
          if (fp >> books >> shipping_method)
            {
              for (int i=0; i < books; i++)
                {
                  if (fp >> price)
                    {
                      subtotal += price;
                    }
                }
            }
    
      if (shipping_method == 'S')
          shipping_price = 4.99;
      else
          shipping_price = 12.99;
    }
    
    //Calculate tax, discount, shipping and total
    
    void calculateOutput(float subtotal, float shipping_price)
    {
      float tax;
      tax = subtotal * .05;
      float discount;
      if (subtotal < 50)
        discount = 0.00;
      else if (subtotal >= 50 && subtotal <= 100)
          discount = subtotal * .10;
      else
          discount = subtotal * .15;
    
      float total;
      total = subtotal + tax - discount + shipping_price;
    }
    //Display a final summary
    void displaySummary(float tax, float subtotal, float discount, float shipping_price, float total)
    {
      cout << "The summary for the order is as follows:" << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Subtotal:" << subtotal << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Tax:" << tax << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Discount:" << discount << endl;
      cout << fixed << showpoint << setprecision (2);
      cout << "Shipping:" << shipping_price << endl;
      cout << fixed << showpoint << setprecision(2);
      cout << "Total:" << total << endl;
    }
    
    int main ()
    {
    
      programOverview ();
    
      cout << "Book Sale Calculator" << endl;
      cout << "=======================" << endl;
    
      openFile();
    
      obtainInput();
    
      calculateOutput(float subtotal, float shipping_price);
    
      displaySummary(float tax, float subtotal, float discount, float shipping_price, float total);
    
      return 0;
    }

  13. #13
    Registered User
    Join Date
    May 2010
    Posts
    2,698
    The following code:
    Code:
    calculateOutput(float subtotal, float shipping_price);
    This is how you define a function, not call it. To call the function you don't need the float. However you will need to define the variables before function call. And when you define your variables always initialize them to some value.

    Code:
    float subtotal = 0.0;
    float shipping_price = 0.0;
    calculateOutput(subtotal, shipping_price);
    Also you should be passing these variables by reference so any changes you make inside the functions will be available after the function returns. So your function definition should look like:
    Code:
    void calculateOutput(float &subtotal, float &shipping_price)
    {
    Notice the ampersands.


    Jim

  14. #14
    Registered User
    Join Date
    Feb 2011
    Posts
    12
    Okay, I did this for both functions that required passing the variables by reference. Thank you for pointing that out to me.

    While there are no errors that coming up when I compile the program. It is not running correctly. The program stops running before the external file is open. Does fp have to be pass by reference as well?

  15. #15
    Registered User
    Join Date
    May 2010
    Posts
    2,698
    Yes you will need to pass a reference to the ifstream to every function that is doing anything with the file. Also your displaySummary() function should have the variables passed by value not reference, since you don't want this function to change the values.

    Jim
    Last edited by jimblumberg; 04-22-2011 at 09:12 PM.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 01-03-2007, 02:02 PM
  2. Trouble with file input
    By w274v in forum C Programming
    Replies: 6
    Last Post: 12-18-2005, 03:40 AM
  3. Trouble storing file input in array
    By difficult.name in forum C Programming
    Replies: 1
    Last Post: 10-10-2004, 11:54 PM
  4. Obtaining a txt file through the web
    By robid1 in forum C Programming
    Replies: 7
    Last Post: 10-24-2003, 05:34 AM
  5. Having trouble with file input...
    By Xaviar in forum C++ Programming
    Replies: 2
    Last Post: 12-10-2002, 11:55 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21