Trouble performing calculations from loaded TXT file using C++ loop - c++

First off, I'll mark this as a homework problem I've been stuck on for a week as I can't seem to figure out what I'm doing wrong and I'm hoping the wonderful people at SO can come to my rescue yet again (I've searched SO and other C++ sites for the past week but the solutions offered didn't correct the issue - however it is possible I may have been setting the loop incorrectly.
The assignment: given a text file numbers.txt (which contains 9,999 numbers ranging from 1 to 10,000 randomly sorted with one number missing from the consecutive list) the assignment is to use a void function in order to determine what the missing integer is.
What I've tried: My last attempt of this contains the following code:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
void find_number();
int main()
{
...
find_number();
}
void find_number();
{
int sum = 0;
int sum1 = 0;
int num;
for (int i = 1; i <= 10000; i++)
sum += i;
cout << "The sum of all the numbers between 1 and 10,000 is: " << sum << endl;
ifstream numbers;
numbers.open("numbers.txt");
if (!numbers.good()) {
return;
cout << "Error! Unable to open file!";
}
if (numbers) {
numbers >> num;
sum1 += num;
}
numbers.close();
cout << "The sum of all the numbers contained in the text file \"numbers.txt\" is: " << sum1 << endl;
cout << "By subtracting the sum of the text file from the sum of 1 to 10,000 the consecutive number missing from the text file is: " << sum - sum1 << endl;
}
What am I doing wrong? Thank you for any assistance.

There are at least two mistakes:
The return statement is executed before the diagnostic output
if (!numbers.good()) {
return;
cout << "Error! Unable to open file!";
}
The following lines will execute once instead of reading the whole file:
if (numbers) {
numbers >> num;
sum1 += num;
}
You can improve your code with the following suggestions:
Extract a number and check the stream status at the same time:
while(numbers >> num) sum1 += num;
You don't need to close the file stream it will do it automatically in its destructor.
You can open the file at the file stream initialization time:
ifstream numbers("numbers.txt");

Hint: you are not reading the whole file

Related

Remove '0' from numbers less than and equal 9

How can I have an output of
Sample Input No.1:
9
Sample Output No.1:
1.2.3.4.5.6.7.8.9
If you input numbers less than or equal to 9, the output should be (1.2.3.4.5.6.7.8.9)
And if you input numbers greater than 9, for example:
Sample Input No.2:
20
Sample Output No.2:
01.02.03.04.05.06.07.08.09.10
11.12.13.14.15.16.17.18.19.20
My code below is for Sample Input & Output No.2. I tried adding another for loop for SAMPLE NO.1 but it still reads Sample No.2 code. What should I do?
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int a, num;
cin >> num;
if (num > 100 || num <= 1){
cout << "OUT OF RANGE";
}
else {
for (int a = 1; a < num; a++){
cout << setfill('0') << setw(2) << a << ".";
}
cout << num;
}
}
kind of new to programming, don't know much🥲
As a possible solution, you could read the input as a string, then convert it to an integer.
Use the string length as the field width for the setw manipulator.
This should be able to handle values of (theoretically) arbitrary length.

How can I add items to the output file?

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.

C++ loading numbers from a file then finding the sum

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.

How do I calculate sum and average of numbers from a text.doc

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.

Use ifstream to read a text file with random generated numbers in columns and find the minimum and maximum from the list?

I am creating a school project but seems lost at the moment. Can someone help me figure out my problem? Here's what's going on:
I have a program that outputs a random generated numbers in a text file using ofstream. It is generated with a format of two columns (one column is SalePrice & the second column RegularPrice). My problem is creating a code that will do the following:
Create a function that will read the text file generated by the first program
Find the average of the second column ONLY! (Regular Price) then outputs it in the screen
Find the minimum and maximum of the second column ONLY! (Regular Price) then outputs it in the screen
Please help! I need help how to code the ifstream part, I am new to C++ and have tried all the solutions in many books but doesn't seem to work for my needs? :-( Any help will be greatly appreciated! Thanks in advance!
Here's just the section of my code (not the entirety), it is not giving me an error . . . it is simply not giving me anything:
float SalePrice[userInput];
float RegularPrice;
string cPrice;
string readFile;
int count = 0;
ifstream inputFile;
inputFile.open(fileName);
inputFile >> RegularPrice;
// To get you all the lines and place the line from myfile into the line variable
while(!inputFile.eof() && getline(inputFile, readFile))
{
if (count < userInput)
{
inputFile >> readFile;
readFile += cPrice; // Saves the line in STRING.
//display the line we gathered:
cout << cPrice << endl;
}
++count;
}
avgRPrice = RegularPrice / userInput;
cout << endl;
cout << fixed << setprecision (2);
cout << "The average of all the Regular Prices in the file is: " << avgRPrice << endl;
cout << "The minimum Regular Price in the file is: " << minRPrice << endl;
cout << "The maximum Regular Price in the file is: " << maxRPrice << endl;
EDITED:
Here's my current code for finding the max & min:
int maxRPrice(float RPrice[])
{
if (RPrice > maxRPrice)
maxRPrice = RPrice;
return maxRPrice;
}
int minRPrice(float RPrice[])
{
if (RPrice < minRPrice)
minRPrice = RPrice;
return minRPrice;
}
Here is an improved version of your code which works perfectly for me:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int userInput = 2;
float SalePrice[userInput]; //Make an array
float RegularPrice[userInput]; //Make an array
string readFile;
ifstream inputFile;
inputFile.open("yourFile.txt");
if(!inputFile){ //Check wether the file is open
cout<<"Couldn't open file!" << endl;
return -1;
}
// To get you all the lines and place the line from myfile into the line variable
for(int count = 0; !inputFile.eof() && (count < userInput) ; ++count) //Why are you using a while-loop if you need to count the iterations
{
//
inputFile >> SalePrice[count] >> RegularPrice[count]; //loads column SalePrice/RegularPrice into the array at position 'count'
}
float sumRegularPrice = 0;
for(int i=0; i < userInput; i++)
sumRegularPrice += RegularPrice[i];
float avgRPrice = sumRegularPrice / userInput;
cout << endl;
cout << fixed;
cout << "The average of all the Regular Prices in the file is: " << avgRPrice << endl;
//cout << "The minimum Regular Price in the file is: " << minRPrice << endl;
//cout << "The maximum Regular Price in the file is: " << maxRPrice << endl;
system("pause");
return 0;
}
Why are you loading RegularPrice only once? As far as I got your explanation about the file format (you said one column is SalePrice & the second column RegularPrice), every line might have this content:
3.44 5.99
To get the min and max price you can simply write two functions.
With this input:
3.44 5.99
5.54 8.99
I get this output (in the console):
The average of all the Regular Prices in the file is: 7.490000
If you have some questions don't hesitate to ask me.