• 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

    • BrowserOS 0.46.0 by Razvan Serea BrowserOS is a free, open-source Chromium-based browser that runs AI agents natively, offering a smarter, more productive browsing experience. It supports Chrome extensions and integrates AI agents to automate tasks, fill forms, and streamline workflows. Your data stays on your computer: you can use your own API keys or run local models via Ollama, making it a privacy-first alternative to tools like Perplexity, Comet, or Dia. With built-in productivity tools and app integrations, BrowserOS boosts efficiency while keeping control firmly in your hands. Being Chromium-based, BrowserOS lets you effortlessly import your bookmarks, passwords, and Chrome extensions in just a few clicks. BrowserOS works with OpenAI GPT models, Anthropic Claude, Google Gemini, and local AI models via Ollama or LMStudio. You can use your own API keys and effortlessly switch between providers. BrowserOS Agent Your AI productivity assistant that organizes and manages your browsing effortlessly Quickly list, group, or close tabs Save and resume browsing sessions Search your history and organize bookmarks Switch instantly to the tab you need BrowserOS Navigator – Automate web tasks with ease Navigate websites and search automatically Interact with pages without manual effort Handle repetitive tasks in seconds What makes BrowserOS special Feels like home - same familiar interface as Google Chrome, works with all your extensions AI agents that run on YOUR browser, not in the cloud Privacy first - bring your own keys or use local models with Ollama. Your browsing history stays on your computer Open source and community driven - see exactly what's happening under the hood MCP store to one-click install popular MCPs and use them directly in the browser bar (coming soon) Built-in AI ad blocker that works across more scenarios! BrowserOS 0.46.0 changelog: Run Claude Code & Codex right in your browser — We've extended the agent harness to bring full coding agents into BrowserOS. Claude Code and Codex now come bundled and plug straight into the assistant, so you can drive your browser with the agent — and the subscription — you already use. A brand new experience — A redesigned new tab, a calmer composer, and a rebuilt command center for switching between agents. The whole assistant is cleaner, faster to reach, and easier to live in. New MCP tools — We rebuilt the browser tool surface from the ground up — a tighter, more reliable set of tools for agents to drive the browser. Plus one-click install of BrowserOS as an MCP server into the agents you already run, with automatic URL sync. Chromium 148 — Updated to the latest Chromium base with all recent upstream fixes and security patches. Streamlined — We've pulled back a few features that weren't getting much use — Skills, Soul, and Memory — so we can focus and ship better versions of them soon. Download: BrowserOS 0.46.0 | 181.0 MB (Open Source) Download: BrowserOS for macOS | 485.0 MB Links: BrowserOS Homepage | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Microsoft finally admits its default Windows 11 25H2, 24H2 action broke key legacy component by Sayan Sen Microsoft last week released Windows 11 KB5094126 and KB5093998 as the latest Patch Tuesday updates. Following that the company also published the accompanying dynamic updates under KB5094149, KB5095971, and KB5094156. So far the company has acknowledged two known issues that have popped up after the release which include bugged-out Office apps as well as the Recycle Bin; though there could be more at play too. Speaking of bugs and issues, Microsoft seems to have finally acknowledged a problem that probably has been around for close to a year. That's because back in July of 2025 the company made a default change to the latest Windows 11 versions, wherein it switched to JScript9Legacy on Windows 11 24H2 and later releases. Hence following the release of version 25H2 in October 2025, JScript9Legacy also remained default-enabled. As a result there has been a compatibility issue ever since then. For those wondering, by switching to JScript9Legacy Microsoft intended to improve the security of modern Windows PCs by reducing vulnerabilities tied to legacy scripting like cross-site scripting (XSS), among others. XSS exploits can allow cyber-attackers to attach malicious code onto legitimate websites and use them to execute the code when a potential victim loads such a website. Hence the new JScript9Legacy engine enforced stricter execution policies and improved object handling, which should help mitigate such attacks. Microsoft today has published a new support article detailing the problem. Neowin spotted it while browsing. The company says that JScript global definitions and execution context may fail to persist across scripts, potentially breaking older dependent apps and web-based components that relied on this legacy behavior. In the article Microsoft has confirmed that the issue stems from its move away from the older jscript9.dll engine in favor of jscript9legacy.dll. As mentioned above, while the newer engine was designed to address vulnerabilities and strengthen security it also changes how JScript handles execution context. As a result functions and definitions loaded by one script could no longer remain available to subsequent scripts once execution ended. The company notes that some applications worked correctly on earlier Windows versions because the older JScript engine automatically retained global definitions and execution state between scripts. Under the newer model though that behavior is disabled by default causing certain legacy workloads and polyfill-dependent scripts to fail. Microsoft says it addressed the problem via the KB5077241 update though the fix had not been enabled automatically in the following updates. As such admins must explicitly turn on persistent JScript execution context using a Registry setting that the tech giant shared today. The configuration can be applied to individual processes or system-wide through the FEATURE_ENABLE_PERSISTENCE registry key. The steps have been outlined below: Run the following command to create the feature control registry key: reg add "HKLM\Software\Policies\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_PERSISTENCE" Under this key, create a new DWORD (32-bit) value. Configure the value as follows: To enable persistence for specific processes only: Set the value to 1 for each target process name. To enable persistence for all processes: Add * as the key name and set its value to 1. You can find the official support article here on Microsoft's website.
    • The possibility that milk gathers back into a glass implies that gravity can be 'reversed'.
    • VidCoder 12.20 by Razvan Serea  VidCoder is a DVD/Blu-ray ripping and video transcoding application for Windows. It uses HandBrake as its encoding engine. Calling directly into the HandBrake library gives it a more rich UI than the official HandBrake Windows GUI. VidCoder can rip DVDs but does not defeat the CSS encryption found in most commercial DVDs. You’ll need the NET 8 Desktop Runtime. If you don’t have it, VidCoder will prompt you to download and install it. The Portable version is self-contained and does not require any .NET Runtime to be installed. You do not need to install HandBrake for VidCoder to work. Feature list: Multi-threaded MP4, MKV containers Completely integrated encoding pipeline: everything is in one process and no huge intermediate temporary files H.264, H.265, MPEG-4, MPEG-2, VP8, Theora video Hardware-accelerated encoding with AMD VCE, Nvidia NVENC and Intel QuickSync AAC, MP3, Vorbis, AC3, FLAC audio encoding and AAC/AC3/MP3/DTS/DTS-HD passthrough Target bitrate, size or quality for video 2-pass encoding Decomb, detelecine, deinterlace, rotate, reflect, chroma smooth, colorspace filters Powerful batch encoding with simultaneous encodes Customizable Pickers to automatically pick audio and subtitle tracks, destination, titles and more Instant source previews Creates small encoded preview clips Pause, resume encoding VidCoder 12.20 changes: Updated HandBrake core to 1.11.2. Download: VidCoder 12.20 | 47.0 MB (Open Source) Download: Portable VidCoder 12.19 | 89.3 MB Link: VidCoder Home Page | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      Jordan Smith earned a badge
      Week One Done
    • Reacting Well
      BizSAR earned a badge
      Reacting Well
    • First Post
      AndreaB earned a badge
      First Post
    • Week One Done
      Huge Trailer earned a badge
      Week One Done
    • Week One Done
      Classifyskilleducation earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      590
    2. 2
      +Edouard
      185
    3. 3
      PsYcHoKiLLa
      76
    4. 4
      Michael Scrip
      73
    5. 5
      Steven P.
      66
  • Tell a friend

    Love Neowin? Tell a friend!