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;
Related
Before I ask anything, I should mention that I have a shaky foundation in C++. Let me know if I'm not being clear on anything and I will do my best to clarify.
My coding problem here is reading a series of 24-hour time values, with no seconds included, and storing them into an array of a structure. Reading the hours and minutes in integer format, and storing it into an array of structures is what I'm not understanding with this. In the text file, the first number in each row is the 24-hour time, and the second number is the amount of minutes that I need to modify the time with. I'm stuck frozen at just reading the times in to begin with.
This is the code I have so far.This is the result of the code.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int size = 7;
int i;
struct Times {
int T;
int M;
};
Times clock[7];
ifstream infile;
infile.open("times.txt");
for (i=0; i<size; i++){
infile>>clock[i].T>>clock[i].M;
}
for (i=0; i<size; i++){
cout<<clock[i].T << " "
<<clock[i].M <<endl;
}
}
Here is the contents of the text file:
6:45 39
12:00 73
0:00 4
23:59 1
22:45 70
11:59 1
14:15 95
Here is the updated code which seems to work:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int size = 7;
int i;
char colon;
struct Times {
int hour;
int minute;
int M;
};
Times clock[7];
ifstream infile;
infile.open("times.txt");
for (i=0; i<size; i++){
infile>>clock[i].hour>>colon>>clock[i].minute>>clock[i].M;
}
for (i=0; i<size; i++){
cout<<clock[i].hour << " "
<<colon << " "
<<clock[i].minute << " "
<<clock[i].M
<<endl;
}
}
Note that each line of your file contains three integral values, not two, and that a colon will stop reading in an integral value (formatted input for integrals will skip leading white spaces and even new line characters, but not "leading" colons). If you want to read an integral value that follows a colon, you'll need to skip the colon.
You could do this by reading in the colon into a variable of type char (and ignoring it afterwards). The code could look as follows:
int main()
{
int hour,minute,x;
char colon;
stringstream s { "15:43 10\n16:48 20\n" };
while (s >> hour >> colon >> minute >> x) {
cout << "H:M=" << hour << ":" << minute << "; times=" << x << std::endl;
}
}
Output:
H:M=15:43; times=10
H:M=16:48; times=20
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.
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.
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.
For some reason outfile is not outputting a txt file in Windows. It has worked fine on the Mac (the line that's commented out in the code below), but in Windows I can't get it to output. Any guidance would be greatly appreciated. Thanks!
#include <iostream>
#include <fstream>
using namespace std;
int iNumberOfEmployees(); // this function prompts the user for the number of employees.
int iMissedDays(int employees); // this function prompts the user for the number of days each employee missed and returns the total.
double dAverageMissedDays(int employees, double missedDays); // this function calculates the average missed days per employee.
int main() {
int iGetEmployees = iNumberOfEmployees();
int iGetMissedDays = iMissedDays(iGetEmployees);
cout << "Average missed days: "<< dAverageMissedDays(iGetEmployees,iGetMissedDays) << endl;
// outputs results to a text file
ofstream outfile;
// outfile.open ("/Users/chrisrukan/Documents/CS140/Project 3/output.txt");
outfile.open ("C:\CS140\Project 3\output.txt");
if (outfile.is_open()) {
outfile << "Average missed days: "<< dAverageMissedDays(iGetEmployees,iGetMissedDays);
outfile.close();
}
else {
cout << "Error opening file" << endl;
}
}
int iNumberOfEmployees () {
int iTotalEmployees = 0;
// loop checks that the user doesn't enter a negative number of employees
while (iTotalEmployees <= 0) {
cout << "Enter the number of employees: ";
cin >> iTotalEmployees;
}
return iTotalEmployees;
}
int iMissedDays (int iEmployees) {
int iTotalMissedDays = 0;
int iIndividualMissedDays;
// loop asks the user the missed days for each individual employee
for (int i = 1; i <= iEmployees; i++) {
iIndividualMissedDays = -1;
// loop checks that user doesn't enter a negative number
while (iIndividualMissedDays < 0) {
cout << "Enter employee " << i << "'s number of missed days: ";
cin >> iIndividualMissedDays;
}
iTotalMissedDays += iIndividualMissedDays;
}
return iTotalMissedDays;
}
double dAverageMissedDays (int iEmployees, double dMissedDays) {
return dMissedDays / iEmployees;
}
In windows, file path are separated by \, you also need an extra \ if you need to pass file path as parameter to a function.
EDIT: according to #Benjamin Lindley, forward slashes will work on Windows too provided that the path is right.
There is also no root directory / as in Linux.
outfile.open ("/Users/chrisrukan/Documents/CS140/Project 3/output.txt");
Try to replace the string "/Users/chrisrukan/Documents/CS140/Project 3/output.txt" with windows file path format, absolute path starting from Disk name. e.g.,
"C:\\Users\\chrisrukan\\Documents\\CS140\\Project 3\\output.txt".
Or
`"C:/Users/chrisrukan/Documents/CS140/Project 3/output.txt"`
make sure those directories do exist.
A backslash in C++ is actually language syntax, for example \n means: new line, \t means: tab, in order to actually have a "\" in a string (as it stands right now you have a \C, \P, and \o which by the way all are considered one character each) you must type two \'s, for example
#include <iostream>
int main() {
std::cout << "\\";
}
outputs:
\
Also just a tip, files will automatically (by default if no other path is specified) be outputted/written to wherever the executable is stored.