CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Apr 2013
    Posts
    12

    Sending Data back to Main()

    I am doing a homework assignment (I know there are a lot of those questions here). I am creating a program that takes input from a file and outputs various items in the form of a restaurant invoice to the screen, a file, as well as an error file. I wrote the whole thing and it works. However, now the teacher tells me that she wants Main() to control everything. Meaning, she wants each function to report back to Main() and Main() to call the next function.

    Obviously, this is not ALL the code, just what applies to my question.

    So here are the real questions:

    1) The CalculateBill() function calls the PrintResults() function. How do I get it to send data back to Main() and allow Main() to call the PrintResults() function instead?

    I could use structures, but that will require me to re-write the entire thing and then I will not understand my own code as structures are very new to me. Also, structures have not been taught in class yet and I do not want to go too far outside of what is being taught.

    Is there a way to do this w/o using structures or a ton of global variables?

    So here is what I have for now:

    Code:
    #include <iostream>
    #include <string>
    #include <iomanip>
    #include <fstream>
    
    using namespace std;
    
    ifstream OpenInputfile( string inFilePath );
    ofstream OpenOutputfile( string outFilePath, int fileType );
    void PrintError(ostream & inFile);
    bool ReadInputCheckErrors ( ifstream & inData );
    void CalculateBill( int inAdults, int inChildren, bool inMealType, bool inWeekend, 
                            double inDeposit );
    void PrintResults( ostream & inFile, int inAdults, int inChildren, bool inDeluxeMeal, 
                            bool inWeekend, double inDeposit, double ADULT_DELUXE, 
                            double ADULT_STANDARD, double childDeluxe, double 
                            childStandard, double tACost, double tCCost, double tTCost, 
                            double tSurcharge, double tTaxTip, double tPCost, double 
                            tBalanceDue, double tDiscount, string tDiscountPercent, 
                            double tDiscountBalance );
    bool verboseError	= false;
    bool saveDataFile	= false;
    bool saveErrorFile	= true;
    bool displayBill	= true;
    
    ifstream inData;
    ofstream outData;
    ofstream errData;
    bool deluxe		= 0;
    bool weekend	= 0;
    int numAdults	= 0;
    int numChildren	= 0;
    double deposit	= 0.00;
    Code:
    int main()
    {
    	inData	= OpenInputfile( "Lab6CDataFile-Input.txt" );
    	outData	= OpenOutputfile( "Lab6CDataFile-Output.txt", 1 );
    	errData	= OpenOutputfile( "Lab6CDataFile-Error.txt", 2 );
    
    	while( !inData.eof() ) /* Process all lines of data. */
    	{ 
    		ReadInputLine(inData);
    	}
    
    	if( outData.good() )
    	{
    		if( verboseError )
    		{
    			cout << "Data file written successfully\n\n" << endl;
    		}
    		system("pause");
    	}
    
    	if ( saveErrorFile )
    	{
                 // I want the call to PrintError() to be here.
    	}
    Code:
    ifstream openInputfile( string inFilePath )
    {
    	ifstream inStream;
    	inStream.open( inFilePath, ios::in ); /* Open the inData File. */
    
    	if( !inStream.is_open() ) /* Inputs file couldn't be opened. */
    	{ 
    		cout << "Error: file could not be opened" << "\n\n";
    		system ("pause");
    		exit(1);
    	}
    	if( verboseError ) {
                  cout << "The input file ( " << inFilePath << " ) has been
                  opened successfully!" << "\n\n"; }
    	return inStream; }
    Code:
    void CalculateBill( int inAdults, int inChildren, bool inDeluxeMeal, bool inWeekend, 
                            double inDeposit )
    {
    	if( displayBill )
    	{
    		const double ADULT_DELUXE		= 25.80;
    		const double ADULT_STANDARD	= 21.75;
    		const double TIP_TAX_RATE		= .18;
    		const double WEEKEND_SURCHARGE	= .07;
    		double childDeluxe			= ADULT_DELUXE * .6;
    		double childStandard			= ADULT_DELUXE * .6;
    		double tACost				= 0;
    		double tCCost				= 0;
    		double tTCost				= 0;
    		double tSurcharge			= 0;
    		double tTaxTip				= 0;
    		double tPCost				= 0;
    		double tBalanceDue			= 0;
    		double tDiscount				= 0;
    		double tDiscountBalance		= 0;
    		string tDiscountPercent			= "";
    
    		if( inDeluxeMeal )
    		{ /* Total cost of all the deluxe meals. */
    			tACost = ADULT_DELUXE * inAdults;
    			tCCost = childDeluxe * inChildren;
    		}
    		else
    		{ /* Total cost of all the standard meals. */
    			tACost = ADULT_STANDARD * inAdults;
    			tCCost = childStandard * inChildren;
    		}
    
    	// Calculations
    		tTCost = tACost + tCCost; /* Total cost of the food. */
    		if( inWeekend == true )
    		{
    			tSurcharge = tTCost * WEEKEND_SURCHARGE; /* Calculate the surcharge */
    		}
    		tTaxTip = (tTCost + tSurcharge) * TIP_TAX_RATE; /* Calculate the tax and tip. */
    		tPCost = tTCost + tTaxTip + tSurcharge; /* Add up total cost, tax, tip and surcharge. */
    	
    	// Calculate the available discount.
    		if( tPCost < 100.00 )
    		{
    			tDiscount = tPCost * .015;
    			tDiscountPercent = "1.5%";
    		}
    		else if( tPCost < 400.00 )
    		{
    			tDiscount = tPCost * .025;
    			tDiscountPercent = "2.5%";
    		}
    		else
    		{
    			tDiscount = tPCost * .035;
    			tDiscountPercent = "3.5%";
    		}
    
    		tBalanceDue = tPCost - inDeposit; /* Calculate the pre-discount balance due. */
    		tDiscountBalance = tBalanceDue - tDiscount; /* Calculate the post-discount balance due. */
    
    	// Pass calculations to the PrintResults function.
    		if( saveDataFile )
    		{
    			PrintResults( outData, inAdults, inChildren, inDeluxeMeal, 
                            inWeekend, inDeposit, ADULT_DELUXE, ADULT_STANDARD, 
                            childDeluxe, childStandard, tACost, tCCost, tTCost, tSurcharge, 
                            tTaxTip, tPCost, tBalanceDue, tDiscount, tDiscountPercent, 
                            tDiscountBalance );
    		}
    		if( displayBill)
    		{
    			PrintResults( cout, inAdults, inChildren, inDeluxeMeal, inWeekend, 
                            inDeposit, ADULT_DELUXE, ADULT_STANDARD, childDeluxe, 
                            childStandard, tACost, tCCost, tTCost, tSurcharge, tTaxTip, 
                            tPCost, tBalanceDue, tDiscount, tDiscountPercent, 
                            tDiscountBalance );
    		}
    	}
    }
    Code:
    void PrintResults( ostream & inFile, int inAdults, int inChildren, bool inDeluxeMeal, 
                            bool inWeekend, double inDeposit, double ADULT_DELUXE, 
                            double ADULT_STANDARD, double childDeluxe, 
                            double childStandard, double tACost, double tCCost, 
                            double tTCost,  double tSurcharge, double tTaxTip, 
                            double tPCost, double tBalanceDue, double tDiscount, 
                            string tDiscountPercent, double tDiscountBalance )
    {
    		inFile << showpoint << fixed << setprecision (2);
    		if( inDeluxeMeal )
    		{
    			if( inAdults > 0 )
    			{
    				inFile << "$" << setw(7) << tACost << "\t" << inAdults << " Adult Meals" 
    					<< " at " << "$" << ADULT_DELUXE << " each" << endl;
    			}
    			if( inChildren > 0 )
    			{
    				inFile << "$" << setw(7)<< tCCost << "\t" << inChildren << " Child Meals" 
    					<< " at " << "$" << childDeluxe << " each" << endl;
    			}
    		}
    		else
    		{
    			if( inAdults > 0 )
    			{
    				inFile << "$" << setw(7)<< tACost << "\t" << inAdults << " Adult Meals" 
    					<< " at " << "$" << ADULT_STANDARD << endl;
    			}
    			if( inChildren > 0 )
    			{
    				inFile << "$" << setw(7)<< tCCost << "\t" << inChildren << " Child Meals" 
    					<< " at " << "$" << childStandard << endl;
    			}
    		}
    		inFile << "--------" << endl;
    		inFile << "$" << setw(7)<< tTCost << "\t" << "Total Cost of All Meals" << endl;
    	
    		if( inWeekend == true)
    		{
    			inFile << "$" << setw(7)<< tSurcharge << "\t" << "Weekend Surcharge" << endl;
    			inFile << "--------" << endl;
    			inFile << "$" << setw(7)<< tTCost + tSurcharge << "\t" << "Subtotal" << endl;
    		}
    		else
    		{
    		}
    
    		inFile << "$" << setw(7)<< tTaxTip << "\t" << "Tax & Tip" << endl;
    		inFile << "--------" << endl;
    		inFile << "$" << setw(7)<< tPCost << "\t" << "Total Party Cost" << endl;
    		if( inDeposit > 0)
    		{
    			inFile << "$" << setw(7)<< inDeposit << "\t" << "Deposit Received" << endl;
    		}
    		else
    		{
    			inFile << "$" << setw(7)<< "0.00" << "\t" << "Deposit Received" << endl;
    		}
    		inFile << "--------" << endl;
    
    		if( tBalanceDue <= 0 )
    		{
    			double tRefundDue = inDeposit - ( tPCost - tDiscount );
    			inFile << "$" << setw(7) << tDiscount << "\t" << tDiscountPercent 
    				<< " Prompt Payment Discount" << endl;
    			inFile << "--------" << endl;
    			inFile << "$" << setw(7) << tRefundDue << "\t" << "Refund Due" << endl;
    		}
    		else
    		{
    			inFile << "$" << setw(7) << tBalanceDue << "\t" << "Balance Due" << endl;
    			inFile << "$" << setw(7) << tDiscount << "\t" << tDiscountPercent 
    				<< " Prompt Payment Discount" << endl;
    			inFile << "--------" << endl;
    			inFile << "$" << setw(7) << tDiscountBalance << "\t" 
    				<< "Balance Due (If Paid Within Ten Days)" << endl;
    		}
    
    		inFile << endl;
    		inFile << "- - - - - - - - - - - - - - - - - - - - - - -" << endl;
    		inFile << endl;
    }

  2. #2
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Sending Data back to Main()

    You can return multiple values from a function either by wrapping them up in a class or struct and returning an instance of that class or struct, or by passing them in as output parameters. That's a lot of values to pass into a function though. Typically in a case like this you'd create a class that represents the bill. If you haven't got that far yet, you may want to consider globals too.

  3. #3
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Sending Data back to Main()

    Is there a way to do this w/o using structures or a ton of global variables?
    Use pass by reference rather than pass by value so that the function can return data to the calling routine as part of its arguments.

    Any parameter of PrintResults is going to have to be defined at global/main level rather then in CalculateBill. Any variable of CalculateBill that has to be passed to PrintResults will need to be passed to CalculateBill by reference rather than by value. With this number of parameters, it would be so much easier using a struct/class but I understand why you don't want to.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  4. #4
    Join Date
    Apr 2013
    Posts
    12

    Re: Sending Data back to Main()

    Thank you for your quick reply. The problem with that is that the variables do not exist globally or in Main(), so there is nothing to reference. The variables were created in CalculateBill().

  5. #5
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Sending Data back to Main()

    Make them global, change PrintResults so the variables are passed by reference or wrap them up in a class or struct. Those are your only choices.
    Last edited by GCDEF; April 17th, 2013 at 09:03 AM.

  6. #6
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Sending Data back to Main()

    The problem with that is that the variables do not exist globally or in Main(),
    Yes, at the moment. But to fullfil your teacher requirements you now need to define them either in main() and pass by reference to CalculateBill and by value to PrintResults - or globally so you don't need to pass them as parameters at all. If you don't want to use a struct/class then this is your only option.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  7. #7
    Join Date
    Apr 2013
    Posts
    12

    Re: Sending Data back to Main()

    Yes, after talking to my teacher, I found that the easiest way to accomplish this was to not use one function to calculate the invoice. Instead, use individual float functions that return pieces of the invoice. that way I can just send the variables to the print function.

    Thank you for your help. I appreciate it.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured