problem with a loop not acting the way intended

code builds fine, runs properly the first time through the loop, not t

Page 1 of 1

4 Replies - 1030 Views - Last Post: 01 January 2010 - 12:59 PM Rate Topic: -----

#1 woodpryan  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 65
  • Joined: 30-April 09

problem with a loop not acting the way intended

Post icon  Posted 01 January 2010 - 02:19 AM

this program is an experimental budget calculator which calculates a budget for a user in alabama. the user is prompted to create a file with their expenses on it and to enter the full file path and name of that file. then the user is prompted to enter their hours worked in two weeks. the calculator multiplies, considers overtime hours, deducts taxes, gives the user their expected net income, their gross income and then deducts the expenses read from the file to figure out what they will have left over. this is given back to the user as a savings account suggestion.

the code builds properly and works fine if you only want to calculate your budget once. but if you want to recalculate your budget, the second time through it does not read in the expenses from the file. the last line in the code (before ending the loop that encloses almost all of main) before return 0; is infile.close();
this should close the file so that it may be re-opened the second time through. if this line is not included, the program will crash because the file it is trying to read is already open. i can not figure out why it does not read in the expenses the second time through though. can anyone help?

below is the full code of this program. it is well commented, it builds, it runs, and i encourage any prospective helper to do so. please take your time and think about it for a while. i'm going to bed and i will find it tomorrow when i get up. thank you all for your time. it's greatly appreciated:

/********************************************************\
 *  Viaticus an Experimental Budget Calculator		  *
 *	Authored by Ryan Wood Thanks to				   *
 *			 Chris Scrip and Michael Wood			 *
 *	   (C)2009  - ALL RIGHTS RESERVED				 *
 *													  *
 * This program calculates the budget of the user	   *
 *in Alabama by first asking the hours and pay rate	 *
 *for each week in a bi-weekly period. The program	  *
 *then takes the expenses from a file and			   *
 *calculates them, returning the surplus				*
 *as a savings suggestion.							  *
 *													  *
 * Problems with this program include:				  *
 * 1. No user interface.								*
 * 2. Calculates only Alabama users.					*
 * 3. The user can not customize.					   *
 * 4. Alabama tax is slightly overstated.			   *
 *													  *
 * Last updated on October 8th 2009					 *
\********************************************************/
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
#include <fstream>
#include <limits>

using namespace std;

// calculateFica() - Calculate FICA tax.
double calculateFica(double pay, int weeks)
{
	double fica;

	if(pay * weeks < 106800)
		fica = pay * 0.0765;
	else
		fica = (106800 * .0765) / weeks;

	return fica;
}

// calculateState() - Calculate state tax.
double calculateState(double pay, int weeks)
{
	double al;

	if(pay * weeks <= 500)
		al = (pay * weeks * .02) / weeks;
	else if((pay * weeks > 500) && (pay * weeks <= 3000))
		al = ((pay * weeks - 500) * .04 +10) / weeks;
	else
		al = ((pay * weeks - 3000) * .05 + 110) / weeks;

	return al;
}

// calculateFed() - Calculate federal tax.
double calculateFed(double pay, int weeks)
{
	double fed;

	if(pay <= 276)
		fed = 0;
	else if(pay > 276 && weeks <= 400)
		fed = ((pay - 276) * .10);
	else if(pay > 400 && pay <= 1392)
		fed = ((pay - 400) * .15 + 12.4);
	else if(pay > 1392 && pay <= 2559)
		fed = ((pay - 1392) * .25 + 161.20);
	else if (pay > 2559 && pay <= 6677)
		fed = ((pay - 2559) * .28 + 452.95);
	else if(pay > 6677 && pay <= 14423)
		fed = ((pay - 6677) * .33 + 1605.90);
	else	
		fed = ((pay - 14423) * .35 + 4162.17);

	return fed;
}

// calculateTax() - Calculate the federal, state, and fica tax.
void calculateTax(double pay, int weeks, double &fica, double &fed, double &al)
{
	fica = calculateFica(pay, weeks);
	al   = calculateState(pay, weeks);
	fed  = calculateFed(pay, weeks);
}

// calculateGross() - Calculate gross income.
double calculateGross(double hrs, double r)
{
	double grosspay;

	if (hrs > 40)
		grosspay = (hrs - 40) * (1.5 * r) + (40 * r);
	else
		grosspay = hrs * r;

	return grosspay;
}

int main()
{
	char	 choice;
	double   hours1, hours2, tips;
	double   grosspay1;
	double   grosspay2;
	double   grosspay;
	double   rate,  bamatax, fica, fedtax, Netincome;
	double   savings, expense, totalExpenses;
	string   expenseName; // use to read the name of the expense the user puts in the file
	int	  enter;
	ifstream infile; // stream for reading input from a file
	int	  wperyear = 26; //set wperyear to half of 52
	char	 fileName[51];

   cout << setprecision(2) << fixed << showpoint;

	cout << "\n\n\n\t\t\tWelcome to Viaticus 3.1" << endl << endl;

	cout << "Would you like to calculate your budget? [y/n] ";
	cin >> choice;

	// If the user input for choice is invalid, this code executes to error trap.		
	while((choice != 'N') && (choice !='n') && (choice!='Y') && (choice !='y'))
	{
		cout << "invalid response. Restarting Program." << endl << endl;
		cout << "Would you like to calculate your budget? |Y|es or |N|o ";

		cin >> choice;

		continue;
	} // choice != ...

	// If the choice is Y/y this code executes
	while(choice == 'Y' || choice == 'y')
	{
		totalExpenses = 0;

		// Prompt the user to create the program's read in file
	cout << "\n\t\tTo use this software, Create a file that includes your expenses."
		 << "\n\tusing the full path of the file, please enter the name of this file here: " << endl;
	cin  >> fileName;
		infile.open(fileName);
		while(!infile.is_open()) // If the file still does not exist, this code executes and the program terminates
		{
			cout << "\n\tYou have incorrectly entered the name of your file. Please make sure the full file path is entered.";
			cin  >> fileName;
	infile.open(fileName);
		}

		// Prompt the user to enter the total hours they worked in the first week of a two week period
		cout << "\nPlease enter total hours worked in the first week.\t";
		cin >> hours1;

		// Prompt the user to enter the second week of hours worked
		cout << "Please enter total hours worked for the second week.\t";
		cin >> hours2;

		// Prompt the user for their pay rate
		cout << "Please enter pay rate.\t\t\t\t\t";
		cin >> rate;

		cout << "Please enter any non-taxed income\nyou have recieved that you would like to include.\t";
		cin >> tips;

		// Use the function calculateGross to determine gross pay.
		grosspay1 = calculateGross(hours1, rate);
		grosspay2 = calculateGross(hours2, rate);

		// Set gross pay to be equal to the sum of the two times calculateGross was run.
		grosspay = grosspay1 + grosspay2;

		// Calculate the tax.
		calculateTax(grosspay, wperyear, fica, fedtax, bamatax);

		// Subtract taxes from gross pay and adds tips/non-taxed income for the net income
		Netincome = grosspay - fica - bamatax - fedtax + tips;

		// Show the user their gross income, taxes, and net income
		cout << "Gross Income = \t\t\t$" << grosspay << endl << endl;
		cout << "Fica tax = \t\t\t$" << fica << endl;
		cout << "Alabama Inc Tax = \t\t$" << bamatax << endl;
		cout << "Federal inc tax = \t\t$" << fedtax << endl << endl;
		cout << "Net/take home pay = \t\t$" << Netincome << endl << endl;

		// Read in expenses from a file and subtract them from net income.
		// The process is printed on the screen for the user to see.
		do
		{
			infile >> expenseName >> expense;

			if(!infile.eof())
			{
				totalExpenses = expense + totalExpenses;
				cout << expenseName << "\t\t" << expense << "\t\t" << totalExpenses << endl;
			}
		} while (!infile.eof()); //end do/while loop

		// Tell the user thier total expenses
		cout << "\nYour total expenses for the two week period are:\t" << totalExpenses << endl << endl;

		// Calculate the savings or deficites of the user
		savings = Netincome - totalExpenses;

		// Determine if the user has money left over or not enough money to cover the expenses
		if(savings > 0)
			cout << "\tI recommend that you put the following in your savings account:\t" << savings << endl << endl;
		else
			cout << "\tI recomend that you lower your expenses by at least:\t" << savings * -1 << endl << endl;

		// Allow user to update choice so the program will terminate or run again.
		cout << "Would you like to re-calculate your budget? |Y|es or |N|o ";
		cin >> choice;
	   
		// If the user enters an invalid choice, this code executes to error trap.
		while((choice != 'Y') && (choice != 'y')  && (choice != 'N') && (choice != 'n'))
		{
			cout << "invalid response! Can't you follow directions? enter Y for Yes or N for No! ";
			cin >> choice;

			continue;
		} // choice != Y, y, N, n
   
		if(choice == 'Y' || choice == 'y')
		{
			cout << "\nViaticus is finished using your file." << endl;
			cout << "If you would like to alter your expenses before re-running Viaticus, please do so now." << endl;

			cout << "\nPress Enter to continue." << endl;

			// Close the input file so that the second time the program is run
			// the file is not still open and in use when infile.open is run.
			
			std::cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
			std::cin.get();
		}
		infile.close();
	} // Main Loop. choice == y, Y

	return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: problem with a loop not acting the way intended

#2 no2pencil  Icon User is offline

  • Dic Head
  • member icon

Reputation: 5167
  • View blog
  • Posts: 26,849
  • Joined: 10-May 07

Re: problem with a loop not acting the way intended

Posted 01 January 2010 - 02:35 AM

When they say yes to recalculate, couldn't you just check for the file pointer, & if it's there close it.
Was This Post Helpful? 0
  • +
  • -

#3 woodpryan  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 65
  • Joined: 30-April 09

Re: problem with a loop not acting the way intended

Posted 01 January 2010 - 02:51 AM

View Postno2pencil, on 1 Jan, 2010 - 01:35 AM, said:

When they say yes to recalculate, couldn't you just check for the file pointer, & if it's there close it.


i'm still learning. we won't get into pointers untill the new semester starts. this is something i've been working on on my own since the class began.
Was This Post Helpful? 0
  • +
  • -

#4 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 855
  • View blog
  • Posts: 2,338
  • Joined: 20-August 07

Re: problem with a loop not acting the way intended

Posted 01 January 2010 - 04:43 AM

in C++, EOF is represented by an internal flag on a stream. When a stream has any error flag set, you will need to call clear() on your stream before you may re-use it (clear resets flags, it does not touch any data)

When you come to open a new file in your second loop iteration, your stream's EOF flag is still set, so make sure you call infile.clear(); before attempting to read any data.

With that said, you have another even more subtle problem in your program relating to EOF, which I've discussed in some detail here: http://www.dreaminco...topic145699.htm
Was This Post Helpful? 0
  • +
  • -

#5 woodpryan  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 65
  • Joined: 30-April 09

Re: problem with a loop not acting the way intended

Posted 01 January 2010 - 12:59 PM

View PostBench, on 1 Jan, 2010 - 03:43 AM, said:

in C++, EOF is represented by an internal flag on a stream. When a stream has any error flag set, you will need to call clear() on your stream before you may re-use it (clear resets flags, it does not touch any data)

When you come to open a new file in your second loop iteration, your stream's EOF flag is still set, so make sure you call infile.clear(); before attempting to read any data.

With that said, you have another even more subtle problem in your program relating to EOF, which I've discussed in some detail here: http://www.dreaminco...topic145699.htm


putting that just below the loops that encloses almost the entire program (while choice = y) works perfectly. thanks a lot. greatly appreciated.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1