I am a newbie to C++ and I've got my first assignment. We've got a text file that contains 5 employee names, wages, and hours worked.
And this is my code so that my program could read it.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream input;
ofstream output;
string name;
int h;
float w;
int numEployee = 0;
double maxPay, minPay, avgPay;
int gross, adjGross;
//input/output file document path
input.open("/Users/jmduller/Documents/xcode/Lab1/Lab1/Employees.txt");
output.open("/Users/jmduller/Documents/xcode/Lab1/Lab1/Employeesoutput.txt");
//checks if the input file is working
if (input.fail())
{
cout << "Input file failed to open." << endl;
system("pause");
exit(0);
}
//checks if output file is working
if (output.fail())
{
cout << "Output file failed to open." << endl;
system("pause");
exit(0);
}
//prints the name, wage, hours worked of the employees to the output file
while (input >> name >> w >> h)
{
output << setw(5) << name << setw(5) << w << setw(5) << h << endl;
}
system("pause");
return 0;
}
It's reading it properly and giving me the output file that I want but there are missing items. The complete output file should be have the number of employees, max pay, min pay, avg pay, gross pay, and adjusted gross.
Can anyone help me point to the right direction?
Thanks
What you got to do is use some conditions and statements inside your while loop statement (which is reading from the file). Increment your 'numEmployee' variable everytime the loop executes(counts number of entries).
compare the 'w' read to check if it is lower than than the minPay(initialized to something very large) then update minPay otherwise if higher than maxPay(intialized to the least value possible) update maxPay.
Also, add the 'w' to another variable sumPay(initialized to zero) in loop and at the end divide it by numEmployee and you are done.
Just output them into the file before return statement.
Related
this is giving me a wicked headache and was hoping I could find some help. The program is supposed to read in a program of 19 integers, then output the smallest (2nd integer) and largest (5th integer) to the screen. However, all my results yield garbage.
#include iostream>
#include <fstream>
#include <cstdlib>
using std::ifstream;
using std::ofstream;
using std::cout;
using std::endl;
//the goal of this program is to read in numbers from a file, then output the
//highest number and the lowest number to the screen
int main() {
ifstream fileInput;
int nOne, nTwo, nThree, nFour, nFive, nSix, nSeven, nEight, nNine, nTen, //there are 19 numbers in the file
nEleven, nTwelve, nThirteen, nFourteen, nFifteen, nSixteen, nSeventeen,
nEighteen, nNineteen;
cout << "Opening File" << endl;
fileInput.open("Lab12A.txt"); //the file is opened
if (fileInput.fail())
{
cout << "Input file opening failed. \n"; //the fail check doesnt pop up, so the file has been opened.
exit(1);
}
fileInput >> nOne >> nTwo >> nThree >> nFour >> nFive >> nSix >> nSeven >> nEight
>> nNine >> nTen >> nEleven >> nTwelve >> nThirteen >> nFourteen >> nFifteen //this is where they should be extracted
>> nSixteen >> nSeventeen >> nEighteen >> nNineteen;
cout << "The highest number is " << nTwo << endl;
cout << "The lowest number is " << nFive << endl;
fileInput.close();
system("pause");
return 0;
}
I wished to add only a comment but since I can't do that, I leave it as an answer.
I have copied your file and created a text file to try to reproduce your issue. At first everything went well (No issue at all). But with comment from Daniel Schepler, I changed file encoding to UTF8-BOM (You can do that easily from Notepad++ Encoding menu) and tried again. I got same values you posted. I can't give more explanation to exactly how values are to be interpreted but I wish someone with more experience enlighten us here.
First I wanted to thank everyone who looked at and commented on this I greatly appreciate it, the issue was ultimately pinned down to needing a full path to the .txt file as opposed to the relative path I initially posted. For what ever reason, my compiler couldn't recognize the file without it. Seems like a silly mistake but I'm relatively new to this so those are sure to squeak by. Thanks again everyone!
You can use class std::vector pushing the values then sorting the container and finally print the second and fifth elements:
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
int main(){
std::ifstream in("test.txt");
std::vector<int> vecInt;
int value;
while(in >> value)
vecInt.push_back(value);
in.close();
std::sort(vecInt.begin(), vecInt.end());
// second value is at index 1 and fifth value is at index 4
for(auto i(0); i != vecInt.size(); ++i)
if(i == 1 || i == 4)
std::cout << vecInt[i] << std::endl;
std::cout << std::endl << std::endl;
return 0;
}
I am not sure about what you mean with "largest fifth integer".
I posted something on this last night, but I have decided to change my approach slightly as I wasn't fully understanding the code I was trying to use.
I apologise as I know this topic has been done to death but I'd like a little help with the code I've written.
I'm loading a .txt file from my computer with 100 integers in. They are each on new lines.
This is my code so far:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main ()
{
ifstream fout;
ifstream fin;
string line;
ifstream myfile ("100intergers.txt");
if (myfile.is_open())
{
while ( getline(myfile,line) )
{
cout << line << '\n';
}
// Closes my file
myfile.close();
// If my file is still open, then show closing error
if (myfile.is_open())
cerr << "Error closing file" << endl;
exit(1);
}
int y = 0;
int z = 0;
int sum = 0;
double avg = 0.0;
avg = sum/(y+z);
cout << endl << endl;
cout << "sum = " << sum << endl;
cout << "average = " << avg << endl;
// checking for error
if (!myfile.eof())
{
cerr << "Error reading file" << endl;
exit(2);
}
// close file stream "myfile"
myfile.close();
return(0);
}
When I run it I get exit code 1 (as well as a list of my 100 integers).
Which means my if clause isn't the right choice, what's a better alternative?
If I delete that bit completely, it fails to run do to an arithmetic error which I think is 0/0*0
Also I think the code I've written for the .txt file is for words, not numbers, but when I change string to int it really bugs and tells me I have more problems than without.
Finally - after this I want to make an array to calc variance - any tips?
Cheers
Jack
You're reading lines from the file, which you output.
Then you do arithmetic with some variables, all of which have the value zero.
These variables have no connection to the file's contents.
I'll help with the basic loop structure by showing a way to count the numbers in the file:
int main()
{
int value = 0;
int count = 0;
ifstream myfile("100intergers.txt");
while (myfile >> value)
{
count++;
}
cout << "There were " << count << " numbers." << endl;
}
Summing and the rest is left as an exercise.
An interactive C++ program whose input is a series of 12 temperatures from the user. It should write out on file tempdata.dat each temperature as well as the difference between the current temperature and the one preceding it. The difference is not output for the first temperature that is input. At the end of the program, the average temperature should be displayed for the user via cout.
Here is What I have so far:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int counter = 0;
int previousTemp;
ofstream file; //declares a file of type ofstream
file.open("temperaturefile.txt"); //opens the file with open method
int temperature = 0;
int difference = 0;
cout << "Enter 12 temperatutes" << endl;
file << temperature;
while (counter < 12)
{
cin >> temperature;
counter++;
// difference = temperature-previousTemp;
// cout << difference << endl;
//
}
}
You have it commented in your code? I don't understand
difference = temperature-previousTemp;
You can keep track of previousTemp at the end of your loop.
After everything in the loop put
previousTemp=temperature;
I am trying to create a program that ask for sales amount and displays total salary and writes the entry to a file. However my program has is only writing the last entry to the file. I have searched online for 2hours for a solution and cant find one.
I want all of the input to write to my file not just the last one
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
void SavingFile(); //Declartion
void Calculate();
char FileName[20];
double GrossPay;
double TotalSalary;
int employeeID=0;
char response;
int i=1;
int main()
{
SavingFile();
}
void SavingFile()
{
cout << "\nEnter the name of the file you want to create: ";
cin >> FileName;
do
{
employeeID++;
cout << endl << endl << "Enter sales amount for sales person ID " << employeeID <<" : $";
cin >> GrossPay;
Calculate();
cout <<"Sales amount for ID " << employeeID <<" : $" << TotalSalary <<endl;
cout <<endl <<endl;
do
{
ofstream Employee(FileName);
Employee <<"Employee ID: "<< employeeID <<" Sales Amount: $" << TotalSalary <<endl;
cout << endl;
i++;
}
while
(employeeID == i);
cout << "Do you want to process another employee ? (y/n): ";
cin >> response;
}
while ( (response == 'Y') || (response == 'y') );
}
void Calculate() // definition
{
TotalSalary = (GrossPay * .10) + 150;
//return TotalSalary;
}
You are overwriting the file every time you write to it.
If you want to append to the file, you need to open the file using the ios_base::app flag in addition to ios_base::out.
In your code, you must replace this:
ofstream Employee(FileName);
with this:
ofstream Employee(FileName, ios_base::out | ios_base::app);
To learn more, you can read this page on the constructor of the ofstream class. Among other things, you will find a description of the various flags you can use and what they mean.
I won't rewrite your code for you, but I'll explain the logic that you need to rewrite.
In a loop, you read a value, and call Calculate, which sets a global variable called TotalSalary. The cout probably looks ok. Try adding a cout into the while loop where you are outputting the file, and you'll see that the values aren't what they used to be.
The problem is that every time you call Calculate, you overwrite TotalSalary. You're not saving these values anywhere, but by looping through, you're assuming that the values are still there.
The solution is to write to the output file at the same time as you write to your cout. Open the ofstream at the top of main, and just output to there like you are outputting to cout.
There's no need to open the file each time in a loop, and in fact you shouldn't. (Though appending would help, if that's what you should have been doing.)
I was asked to write a program to open a txt.doc and find the: number of numbers in the list, the sum and the avg. With I compile the code my valves equal zero. I cant find out where I went wrong.
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
string filename;
int valve;
int aNumber = 0;
int numbers = 0;
double sum = 0.0;
double average = 0.0;
// get file from user
cout << "enter the filename\n";
cin >> filename;
cout << "_________________________________________\n";
// open file
inputFile.open(filename.c_str());
// if loop(if the file successfully opened, process it.)
if (inputFile)
{
while (inputFile >> valve)
{
cout << valve << endl;
}
}
else
{
//display an error message
cout << "Error opening the file\n";
}
cout << "\n";
while (inputFile >> aNumber)
{
numbers++;
sum += aNumber;
}
if (numbers > 0)
average = sum / numbers;
else
average = 0.0;
cout << "Number of numbers: " << numbers << "\n";
cout << "Sum is: " << sum << "\n";
cout << "Average is: " << average;
inputFile.close();
return 0;
}
I don't know why my "numbers" "sum" "average" = zero.
The problem with your code is that you try to read the same file multiple times without getting it off the end: once the stream converts to false it will stay in this state until the stream state is cleared and ignore any real file operations. Also, even if you clear() the file's state it would go immediately back into failure state when an attempt to read data is made because either the next value is misformatted or the end of the stream is reached. You could clear() the state and seekg() to the beginning of the file, though (although I'm not recommending this approach):
while (inputFile >> value) {
...
}
inputFile.clear(); // clear any state flags
inputFile.seekg(0, std::ios_base::beg);
Reading files is generally fairly expensive, not to mention that some sources for "files" can't be read multiple times (for example, a named pipe looks like a file but can be only read once). The cost comes from both the need to access the physical media and the, if that access is fast, the conversion internal to the program. Thus, you are best off to read the file just once and do all of the relevant calculations in the same pass. If combining these operations is deemed unreasonable, you might want to load the content into a container and then operated on the container:
std::vector<double> values{ std::istream_iterator<double>(inputFile),
std::istream_iterator<double>() };
// now use values
In case you'd argue that the file is large: in this case you actually do not want to read the file more than once nor do you want to store it in a container, i.e., you'd process the file in a single pass. For the task at hand doing so is fairly trivial and certainly quite feasible.