• 0

Need help using a file (C++)


Question

I decided to take an online C++ class, and at first I was doing well but now I seem to be behind. I have read the chapters a few times and think I may have this one but I am probably completely off base. Here is the problem:

Design an algorithm that will read a file of employee records and produce a weekly report of gross earnings for those employees. Fross earnings are earnings before tax and other deductions. Each input record contains the employee number, the hours worked, and the rate of pay. At the end of the report print the total gross earnings for that week.

He did not give us a file to input from so it is hard to check to see if it worked. Here is what I have so far:

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <iomanip>

using namespace std;

int main()
{
    {float GrossEarnings, TotalGrossEarnings, rate;
    int hours;
    unsigned int EmployeeNumber;
    ifstream infile;  // Declare file stream named infile.

    infile.open ("grossearnings.txt",ios::in); //Oppem file for input

    TotalGrossEarnings = 0.0;
    GrossEarnings = 0.0;
    rate = 0;
    hours = 0;

    cout << "This is the Employees Gross Earnings:\n";

    if (infile) // If no error occurred while opening file
     {
                cout.setf(ios::fixed);
                cout << "The number in the data file are as follows:\n"
                << setprecision(1);

     do
       {
                infile >> EmployeeNumber >> hours >> rate;     // Get number from file.
                cout << EmployeeNumber << GrossEarnings <<  endl;
                GrossEarnings = rate * hours;

                } 
                while(EmployeeNumber != 0.0);

      TotalGrossEarnings = TotalGrossEarnings + GrossEarnings;
      cout << "Total Gross Earnings are:" << TotalGrossEarnings <<endl;


    system ("PAUSE");

    return 0;
       }}}

Am I completly off base? Thank You!

Shadow

Link to comment
https://www.neowin.net/forum/topic/878628-need-help-using-a-file-c/
Share on other sites

5 answers to this question

Recommended Posts

  • 0

I don't have time to proof-read your code at the moment, but:

- test it. Write a txt file containing what you think the records should look like, and make the program use it.

- use code tags when you post code in a forum, otherwise it's almost impossible to read.

  • 0

Unfortunately I'm not so good with file reading or the iomanip library, so that's going to be up to you.

I did you a little service and cleaned up your code. If someone like Dr.Asik comes back and is able to review your code for you (or is willing. Keep in mind, we don't do your homework for you, here) then at least now it will be readable and, assuming you properly use your functions and such, functional.

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <iomanip>
using namespace std;

int main()
{
    float GrossEarnings, TotalGrossEarnings, rate;
	GrossEarnings = TotalGrossEarnings = rate = 0.0; //assign 0.0 to ALL float values listed. Much easier to read.
    int hours = 0;
    unsigned int EmployeeNumber = 0; // assigning values on instantiation improves organization as well.
    ifstream infile;  // Declare file stream named infile.

    infile.open("grossearnings.txt",ios::in); //Open file for input
    cout << "This is the Employees Gross Earnings:\n";

    if (infile) // If no error occurred while opening file
	{
		cout.setf(ios::fixed);
		cout << "The number in the data file are as follows:\n" << setprecision(1);
	} //You were missing a bracket here.

	while(EmployeeNumber != 0.0) // I find do/while loops to be sloppy so a while loop makes the code more clean.
	{
		infile >> EmployeeNumber >> hours >> rate; // Get number from file.
		cout << EmployeeNumber << GrossEarnings << "\n";
		GrossEarnings = rate * hours;
	}

	TotalGrossEarnings += GrossEarnings; //+= returns the sum of the right and left operand and returns value to left operand.
	cout << "Total Gross Earnings are: " << TotalGrossEarnings << "\n";

    cout << "Press any key to exit.\n";
    cin.get();  //A lot of people argue against using the system("pause") command, it is better in many cases to use cin.get();
    return 0;
}

I'm not trying to nitpick at your code or anything, don't get me wrong.

You should have a look at the changes I made. Most of what I did greatly improves your organization, and makes the code much easier for others to use.

I can't really test this myself since I really don't know what you expect to be done with the file to be read from, but you might be able to put something together and give this a whirl.

Otherwise, Dr.Asik may be able to help.

Good luck. :yes:

  • 0

Unfortunately I'm not so good with file reading or the iomanip library, so that's going to be up to you.

I did you a little service and cleaned up your code. If someone like Dr.Asik comes back and is able to review your code for you (or is willing. Keep in mind, we don't do your homework for you, here) then at least now it will be readable and, assuming you properly use your functions and such, functional.

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <iomanip>
using namespace std;

int main()
{
    float GrossEarnings, TotalGrossEarnings, rate;
	GrossEarnings = TotalGrossEarnings = rate = 0.0; //assign 0.0 to ALL float values listed. Much easier to read.
    int hours = 0;
    unsigned int EmployeeNumber = 0; // assigning values on instantiation improves organization as well.
    ifstream infile;  // Declare file stream named infile.

    infile.open("grossearnings.txt",ios::in); //Open file for input
    cout << "This is the Employees Gross Earnings:\n";

    if (infile) // If no error occurred while opening file
	{
		cout.setf(ios::fixed);
		cout << "The number in the data file are as follows:\n" << setprecision(1);
	} //You were missing a bracket here.

	while(EmployeeNumber != 0.0) // I find do/while loops to be sloppy so a while loop makes the code more clean.
	{
		infile >> EmployeeNumber >> hours >> rate; // Get number from file.
		cout << EmployeeNumber << GrossEarnings << "\n";
		GrossEarnings = rate * hours;
	}

	TotalGrossEarnings += GrossEarnings; //+= returns the sum of the right and left operand and returns value to left operand.
	cout << "Total Gross Earnings are: " << TotalGrossEarnings << "\n";

    cout << "Press any key to exit.\n";
    cin.get();  //A lot of people argue against using the system("pause") command, it is better in many cases to use cin.get();
    return 0;
}

I'm not trying to nitpick at your code or anything, don't get me wrong.

You should have a look at the changes I made. Most of what I did greatly improves your organization, and makes the code much easier for others to use.

I can't really test this myself since I really don't know what you expect to be done with the file to be read from, but you might be able to put something together and give this a whirl.

Otherwise, Dr.Asik may be able to help.

Good luck. :yes:

This is great! I am definitely not looking for someone to do my work, just someone to explain (like you did) where I may have gone astray. I am going to spend the weekend rereading all the chapters to see if I can get a better grasp on this, but you certainly have helped me.

  • 0

This is great! I am definitely not looking for someone to do my work, just someone to explain (like you did) where I may have gone astray. I am going to spend the weekend rereading all the chapters to see if I can get a better grasp on this, but you certainly have helped me.

Well, you can start by using an IDE. The code you originally posted was full of formatting errors and wouldn't even compile. As for your assignment, consider organizing related data into structures or classes. And Employee structure might look something like this:

struct Employee
{
	unsigned int EmployeeNumber;
	float Rate;
	float GrossEarnings;
};

One benefit of this is that the Employee structure above is of fixed-length: is this case 12 bytes (both ints and floats are 4 bytes). This makes it easy to store records in a file and is similar to how a database stores records. Moving one record forward simply involves incrementing a pointer to the structure. Furthermore, if you had a record file that was 36 bytes long, you could infer that it contained 3 Employee structures.

  • 0

Well, you can start by using an IDE. The code you originally posted was full of formatting errors and wouldn't even compile. As for your assignment, consider organizing related data into structures or classes. And Employee structure might look something like this:

struct Employee
{
	unsigned int EmployeeNumber;
	float Rate;
	float GrossEarnings;
};

One benefit of this is that the Employee structure above is of fixed-length: is this case 12 bytes (both ints and floats are 4 bytes). This makes it easy to store records in a file and is similar to how a database stores records. Moving one record forward simply involves incrementing a pointer to the structure. Furthermore, if you had a record file that was 36 bytes long, you could infer that it contained 3 Employee structures.

Thank you again... I understand what you are saying and like the logic behind it. We actually have not gotten into pointers or structures, but that won't keep me from using it in the homework.

You guys are great

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Anybody that thinks flying cars were possible are idiots. Everyone would basically need a pilot licence, can you imagine how insane and dangerous that would be, people can barely handle driving on land safely right now.
    • Microsoft Edge 149.0.4022.80 by Razvan Serea Microsoft Edge is a super fast and secure web browser from Microsoft. It works on almost any device, including PCs, iPhones and Androids. It keeps you safe online, protects your privacy, and lets you browse the web quickly. You can even use it on all your devices and keep your browsing history and favorites synced up. Built on the same technology as Chrome, Microsoft Edge has additional built-in features like Startup boost and Sleeping tabs, which boost your browsing experience with world class performance and speed that are optimized to work best with Windows. Microsoft Edge security and privacy features such as Microsoft Defender SmartScreen, Password Monitor, InPrivate search, and Kids Mode help keep you and your loved ones protected and secure online. Microsoft Edge has features to keep both you and your family protected. Enable content filters and access activity reports with your Microsoft Family Safety account and experience a kid-friendly web with Kids Mode. The new Microsoft Edge is now compatible with your favorite extensions, so it’s easy to personalize your browsing experience. Microsoft Edge 149.0.4022.80 changelog: Fixes Fixed an issue that prevented QR code generation from working. Feature updates Intune MAM Protected Downloads. The protected downloads feature for Intune MAM will now save downloaded files to the Documents > Microsoft Edge > Downloads folder in OneDrive. Extensions monitoring in the Edge management service. The Microsoft Edge management service now allows admins to gain visibility into extensions installed across their managed users. From the extensions monitoring page, admins can see which extensions have been installed as well as manage user requests for blocked extensions. For more information, see Microsoft Edge Extensions Monitoring. Validate Edge builds early with enterprise preview. Enterprise preview provides a simpler way for admins to flight pre-release Edge builds to their users. To reduce friction and bolster usage, users will receive pre-release builds directly inside of their Stable Edge application. Admins can allow users to easily opt-out of the preview experience, using built-in rollback to switch between their pre-release and stable channels with ease. Microsoft 365 admin center users can configure the feature, view their flighting population, and receive personalized recommendations all in one place. For more information, see Get started with Enterprise Preview in Microsoft Edge. Download: Microsoft Edge (64-bit) | 193.0 MB (Freeware) Download: Microsoft Edge (32-bit) | 170.0 MB Download: Microsoft Edge (ARM64) | 188.0 MB View: Microsoft Edge Website | Release History Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • The machines are starting to fight back any way they can.
    • No news articles about the Arch Linux repo being majorly infected with malware?!?
    • Waymo recalls self-driving software after cars enter closed freeway work zones by Paul Hill Waymo, the self-driving car maker owned by Alphabet – the parent company of Google –, has recalled some of its fifth-generation Automated Driving Systems (ADS). It did so after some of its cars drove through closed construction zones. According to the National Highway Traffic Safety Administration (NHTSA), the affected vehicles were capable of driving through a closed freeway construction zone and continuing to drive at speed. The listing on the NHTSA website says that Waymo is currently developing a solution to fix this issue, but in the meantime, freeway driving is being restricted. Waymo will update its ADS software so that vehicles can detect when they can avoid entering construction zones. According to the Safety Recall Report, on April 20, 2026, Waymo’s Field Safety Committee began meetings reviewing an event from April 11, 2026, and five events from April 19, 2026, where Waymo’s autonomous vehicles didn’t recognize and drove past ramp closure signs into the pre-planned freeway construction zones. This took place in Phoenix, Arizona. Separately, on May 18, 2026, seven Waymo vehicles entered freeway lanes with active construction in the San Francisco Bay Area by driving between cones that were placed to show the lane was closed. On the back of both of these events, Waymo restricted freeway driving until it could address the issue. In June, Waymo’s Safety Board reviewed the issue and additional information related to ADS performances around construction zones; then, as a result, it decided to conduct a recall. This development is not good for Waymo as it adds to a growing list of technical hiccups its cars have experienced. Ultimately, it will lead to more scrutiny from lawmakers around the world who will be more cautious about letting autonomous vehicles on their roads without tighter regulation. For readers in areas where Waymo operates, does this news make you more wary about stepping into one of these vehicles?
  • Recent Achievements

    • Week One Done
      Eurosoft10 earned a badge
      Week One Done
    • One Month Later
      Eurosoft10 earned a badge
      One Month Later
    • One Year In
      Skeet Campbell earned a badge
      One Year In
    • One Month Later
      Sharbel earned a badge
      One Month Later
    • First Post
      BizSAR earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      599
    2. 2
      +Edouard
      190
    3. 3
      PsYcHoKiLLa
      79
    4. 4
      Michael Scrip
      77
    5. 5
      Steven P.
      69
  • Tell a friend

    Love Neowin? Tell a friend!