Using functions properly - c++

I'm trying to use functions to process data from a .dat file, but I can't seem to get the functions to read the data correctly. On line 62, it's trying to calculate the low, high and average of the different temperatures recorded at three different heights, but the functions aren't processing any data. The average function should be dividing the total of the numbers by the count of the numbers, but it's not doing that. Plus, I can't get high or low to work. What am I doing wrong?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <conio.h>
#include <string>
using namespace std;
double qMeter = 0;
double hMeter = 0;
double oneMeter = 0;
int solDay = 0;
string garbage;
string localTime;
string decSol;
ifstream input;
ofstream output;
//function prototypes
double low(double lowTemp);
double high(double highTemp);
float average(double avgTemp);
int main()
{
input.open("curiosity234x.dat"); //opens input data file
output.open("output.dat"); //opens output data file
for (int i = 0; i < 4; i++) //gets rid of the first four lines
{
getline(input,garbage);
cout << endl;
}
while (!input.eof())
{
int count;
double newOneMeter;
double newHMeter;
double newQMeter;
if (solDay == 2) //processes data for the second solar day
{
input >> solDay >> localTime >> decSol
>> newOneMeter >> newHMeter >> newQMeter;
oneMeter = oneMeter + newOneMeter;
hMeter = hMeter + newHMeter;
qMeter = qMeter + newQMeter;
count++;
output << solDay << fixed << setprecision(1) << setw(5)
<< "Solar" << "Average" << "Low" << "High"
<< "Average" << "Low" << "High"
<< "Average" << "Low" << "High"
<< "Day" << "Temp" << "Temp" << "Temp" << "Temp" << "Temp"
<< "Temp" << "Temp" << "Temp" << "Temp"
<< fixed << setprecision(15) << "1 meter" << ".5 meters"
<< ".25 meters"
<< average(oneMeter) << low(oneMeter) << high(oneMeter)
<< average(hMeter) << low(hMeter) << high(hMeter)
<< average(qMeter) << low(qMeter) << high(qMeter);
}
if (solDay == 3) //processes data for the third solar day
{
input >> solDay >> localTime >> decSol
>> newOneMeter >> newHMeter >> newQMeter;
oneMeter = oneMeter + newOneMeter;
hMeter = hMeter + newHMeter;
qMeter = qMeter + newQMeter;
count++;
output << solDay << fixed << setprecision(1) << setw(5)
<< "Solar" << "Average" << "Low" << "High"
<< average(oneMeter) << low(oneMeter) << high(oneMeter)
<< average(hMeter) << low(hMeter) << high(hMeter)
<< average(qMeter) << low(qMeter) << high(qMeter);
}
}
cout << endl << "The output.dat file has been written and transmitted.";
/*
reads first line. Assigns first string to 'int solDay'
second to 'string time', third to decSol, fourth to oneMeter,
fifth to hMeter and sixth to qmeter. Meters should have setw().
*/
getch();
return 0;
input.close();
output.close();
}
//functions used in main
double low(double lowTemp)
{
int test = 10,000;
double least;
if (lowTemp < test)
{
lowTemp = test;
lowTemp = least;
}
return least;
}
double high(double highTemp)
{
int test = 10,000;
double most;
if (highTemp < test)
{
highTemp = test;
highTemp = most;
}
return most;
}
float average(double avgTemp)
{
avgTemp = avgTemp / count;
return avgTemp;
}

Look at the implementation of low for example:
int test = 10,000;
double least;
if (lowTemp < test)
{
lowTemp = test;
lowTemp = least;
}
return least;
If the if block executes, you assign the uninitialized least to lowTemp. And then regardless of whether it executes or not, you return the uninitialized least.
Why would you assign test to lowTemp only to then overwrite it with least?
Also 10,000 is not a integer literal representing ten thousand. You cannot put a comma in your literals to separate thousands. You must write 10000.

Related

How to find Maximum number and negative numbers from a .txt file and also how to output Total result to another .txt file

I want to find Maximum numbers from my "numbers.txt" file and amount of negative numbers. And i want to output the Total result to another .txt file and console and the rest to the console only.
Im very new and just cant figure out how to do it.
This is what i have now
a "numbers.txt" file with
-4
53
-5
-3
2
and
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int n = 0;
int sum = 0, total = 0;
fstream file("numbers.txt");
while (file >> n)
{
sum += n;
total++;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
int Highest;
int Negative;
cout << "Total result: " << sum << endl;
cout << "Numbers added: " << AmountOfNumbersAdded << endl;
cout << "Average number: " << average << endl;
cout << "Maxiumum number: " << endl;
cout << "Negative numbers: " << endl;
return 0;
}
i tried to do
float Highest = INT_MIN;
if (Highest < num[i]) {
Highest = num[i];
but it just wouldn't work.
You don't need to store the numbers to find the maximum or the amount of negative numbers, but you need to track them inside the loop, like you're already doing with the sum and the total amount of numbers.
int Highest = INT_MIN;
int Negative = 0;
while (file >> n)
{
sum += n;
total += 1;
if (n < 0)
{
Negative += 1;
}
if (n > Highest)
{
Highest = n;
}
}
float average = (float)sum / total;
Here's what you're looking for.
#include <iostream>
#include <fstream>
int main()
{
int n = 0;
int sum = 0, total = 0;
int highest = 0;
int negatives = 0;
std::fstream file("numbers.txt");
while (file >> n)
{
if (n > highest) highest = n;
if (n < 0) ++negatives;
sum += n;
++total;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
std::cout << "Total result: " << sum << "\n";
std::cout << "Numbers added: " << AmountOfNumbersAdded << "\n";
std::cout << "Average number: " << average << "\n";
std::cout << "Maxiumum number: " << highest << "\n";
std::cout << "Negative numbers: " << negatives << "\n";
file.close();
return 0;
}
As you're new, few advices for you:
Never use using namespace std.
Prefer using "\n" instead of std::endl.
Don't forget to close any files/database after opening them like you did in your code.
Always try to avoid macros.

C++ That Is Plaguing Me To This Day

What is the correct solution?
What is the correct solution?
What is the correct solution?
My Code (which is obviously wrong):
<iostream> and <fstream> libraries are included.
int main() {
int num = 0;
int totalCount = 0;
std::ifstream inFile;
double average = 0.0;
int totalTwo = 0;
double total = 0.0;
const double VALUE_ONE = 858.5;
std::cout << "What is the number? ";
std::cin >> num;
std::cout << std::endl;
inFile.open("numbers.txt");
while (inFile >> num) {
totalCount += num;
}
total = num * VALUE_ONE;
average = total/totalCount;
totalTwo = total * num;
inFile.close();
return 0;
}
numbers.txt
When you do this:
std::cin >> num;
std::cout << std::endl;
inFile.open("numbers.txt");
while (inFile >> num) {
totalCount += num;
}
you're reading into num and then immediately overwriting it with data from the input file. Use two variables for the two inputs.
Your code doesn't really match what the instructions say to do.
You are reading the user's chosen multiplier into num, and then you are reading the numbers from the text file into num as well, losing the multiplier. And you are not keeping track of how many numbers are read from the file, which you need in order to calculate the average.
You need to add a few more variables to your code to separate things. Also, there is no need for your VALUE_ONE constant at all.
Try something more like this:
#include <iostream>
#include <fstream>
int main()
{
int multiplier = 0;
int total = 0, totalTwo = 0;
int quantity = 0;
int num = 0;
double average = 0.0;
std::cout << "After all numbers are read, what number would you like to multiply the total by? ";
std::cin >> multiplier;
std::cout << std::endl;
std::ifstream inFile("numbers.txt");
while (inFile >> num) {
total += num;
++quantity;
}
inFile.close();
average = double(total) / quantity;
totalTwo = total * multiplier;
std::cout << "Total = " << total << "\n" << "Average = " << average << "\n" << "Total * " << multiplier << " = " << totalTwo;
return 0;
}
Live Demo

Various Data Validation File I/O Practices with Arrays and Strings C++

#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
#include <array>
#include <sstream>
using namespace std;
void NumberSummaryList(string);
void Validation(string);
int main()
{
string file = "";
cout << "Hello, what is the name of the number file that you would like to process, please don't forget to include .txt " << "-For Example- data.txt" << endl;
cin >> file;
try
{
ifstream DataIn;
DataIn.open(file);
if (DataIn.is_open() == false)
{
throw 20;
}
}
catch (int e)
{
cout << "An error has occurred with opening the file." << endl;
}
NumberSummaryList(file);
Validation(file);
}
void NumberSummaryList(string file)
{
ifstream DataIn;
DataIn.open(file);
const int NumbersArray = 100;
int numbers[NumbersArray];
int count;
int x;
int min = 0;
int max = 0;
int temp = 0;
float sum = 0;
float avg = 0;
count = 0;
while (!DataIn.eof())
{
DataIn >> numbers[count];
count++;
}
x = count;
DataIn.close();
for (int count = 0; count < x; count++)
{
cout << numbers[count] << "\n";
}
min = numbers[0];
max = numbers[0];
for (int count = 0; count < x; count++)
{
temp = numbers[count];
if (temp < min)
min = temp;
if (temp > max)
max = temp;
}
for (int count = 0; count < x; count++)
{
sum += numbers[count];
}
avg = sum / x;
ofstream OutData;
OutData.open("listsummary.txt");
cout << "The total of numbers read in the data file is " << x << endl;
cout << "The average of all numbers in the data file is " << avg << endl;
cout << "The max value of the data file is " << max << endl;
cout << "The min value of the data file is " << min << endl;
OutData << "The total of numbers read in the data file is " << x << endl;
OutData << "The average of all numbers in the data file is " << avg << endl;
OutData << "The max value of the data file is " << max << endl;
OutData << "The min value of the data file is " << min << endl;
OutData.close();
}
void Validation(string file)
{
ifstream DataInStrings;
DataInStrings.open(file);
int count = 0;
string stringarray[100];
int intarray[100];
int y = 0;
for (int count = 0; count < 100; count++)
{
getline(DataInStrings, stringarray[count]);
if (stringarray[count].length() > 5)
{
cout << "Error Found! The element in position " << count + 1 << " " << stringarray[count] << " is too long. Error Written." << endl;
}
else
{
}
}
for (int count = 0; count < 100; count++)
{
string CopyofArray;
CopyofArray = stringarray[count];
int intcopy = stoi(CopyofArray);
if (intcopy < 0)
{
cout << "Error Found! The element in position " << count + 1 << " " << stringarray[count] << " is negative. Error Written." << endl;
}
else
{
}
}
for (int count = 0; count < 100; count++)
{
cout << stringarray[count] << "\n";
}
string ArrayCopy;
ArrayCopy = stringarray[count];
//if (isalpha(ArrayCopy))
//{
//}
//else
//{
// cout << "Alphabetical characters detected in the file, error written." << endl;
//}
DataInStrings.close();
}
Hey guys. This is a project for class that I am stuck on and struggling with. The goal is to validate some of the data inside of the file I load in, which should be numbers 1-100. My teacher has required me to write out errors if the file contains any alphanumericals, symbols like ? or /, if the length of the element is greater than 5, and if the number is negative.
The program is also supposed to display the contents of the file 1-100, find the max, min, average, and total of numbers read.
I have successfully read in the file, found the max, min, average, and total of numbers read. I also have successfully programmed it to write out errors if a number is too long or if it is negative.
However, my trouble comes whenever the file contains either an alphanumerical or a symbol. The file simply won't load and the program won't function correctly if I try to test out putting a alphanumerical or symbol in the data file.
I tried rewriting the program to use getline at first and read in the strings, and then convert when needed. But it now has an issue of where the program will not compute after an alphanumerical is found.
I am here to ask for advice or some type of direction in the right way. My teacher had us write part of the program first, and then added in the data validation parts which angers me because it jumbles the whole thing up in different places.
I look forward to any... please and thanks guys!

How to display whole numbers without decimals

I created a program to display an average from an array of numbers the user have decided to input. The program asks the user the amount of numbers he / she will input, then they input all positive numbers. The output for the average is always a decimal, how can I only display the whole number without any decimal points. Ex. 12.34 = 12 / 8.98 = 8
#include <iostream>
#include <iomanip>
using namespace std;
void sortingTheScores(double *, int);
void showsTheScoresNumber(double *, int);
double averageForAllScores(double, int);
int main()
{
double *scores;
double total = 0.0;
double average;
int numberOfTestScores;
cout << "How many test scores do you have? ";
cin >> numberOfTestScores;
scores = new double[numberOfTestScores];
if (scores == NULL)
return 0;
for (int count = 0; count < numberOfTestScores; )
{
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores[count] <= 0)
{
cout << "Value must be one or greater: " ;
cin >> scores[count];
}
count = count +1;
}
for (int count = 0; count < numberOfTestScores; count++)
{
total += scores[count];
}
sortingTheScores(scores, numberOfTestScores);
cout << "The numbers in set are: \n";
showsTheScoresNumber(scores, numberOfTestScores);
averageForAllScores(total, numberOfTestScores);
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << averageForAllScores(total,numberOfTestScores);
return 0;
}
void sortingTheScores (double *array, int size)
{
int sorting;
int theIndex;
double theNumbers;
for (sorting = 0; sorting < (size - 1); sorting++)
{
theIndex = sorting;
theNumbers = array[sorting];
for (int index = sorting + 1; index < size; index++)
{
if (array[index] < theNumbers)
{
theNumbers = array[index];
theIndex = index;
}
}
array[theIndex] = array[sorting];
array[sorting] = theNumbers;
}
}
void showsTheScoresNumber (double *array, int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
}
double averageForAllScores(double total, int numberOfTestScores)
{ double average;
average = total / numberOfTestScores;
return average;
}
You can use I/O manipulators here:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setprecision(0) << 1.231321 << '\n';
}
Output:
1
You can do it without using iomanip library:
std::cout.precision(0);
std::cout << 1.231321 << std::endl;
Then you'll simply get:
1
Just you need to use std::cout.precision() which is equivalent to std::setprecision() from iomanip library.
Edit:
The aforementioned solution is okay for smaller floating point values, but if you try something like 1334.231321, the std::cout will result displaying some scientific notation, something like:
1e+03
which is actually odd to read and understand. To solve it, you need std::fixed flag, you may write something like:
std::cout.precision(0), std::cout << std::fixed;
std::cout << 1334.231321 << std::endl;
Then it'll show:
1334
For numbers in a +/-2^31 range you can do:
cout << int(12.34) << " " << int(8.98) << endl;
which produces output
12 8
You may also want to consider rounding to the nearest integers. To do so
add a line
#include <cmath>
then do
cout << int(rint(12.34)) << " " << int(rint(8.98)) << endl;
this gives
12 9

passing a two dimensional array to a function from a data file and output contents

This seems simple enough but I'm missing something here to make this code work. What I'm trying to do is print the contents of the two dimensional array in 25 rows and 4 columns with student's num, id, score, and name.
I experimented with something similar to this code when I initialized the array with numbers. But now that I'm reading the data from a file, I've hit a wall and need help.
I tried using the name of the array in the cin object but I got an error message like this:
"assign6.cpp:49:11: error: no match for 'operator>>' (operand types are 'std::ifstream {aka std::basic_ifstream}' and 'const int (*)[4]')"
So I took that out and now the code compiles but I get garbage. Any suggestions? Sorry about not getting back soon. I got caught up in other assignments. I made changes and now the programs works. Here the results.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <fstream>
using namespace std;
//const
const int Array_Row = 25;
const int Array_Col = 4;
//arrays
string letterGrade[Array_Row];
int myScores[Array_Row][Array_Col];
string names[Array_Row];
int main()
{
int count;
//int average;
ifstream inFile;
inFile.open("classData.txt");
int arraySize = 0;
if(inFile.is_open())
{
int counter = 0;
while(inFile.eof()==false)
{
inFile >> myScores[counter][0];
inFile >> myScores[counter][1];
inFile >> myScores[counter][2];
inFile >> myScores[counter][3];
getline(inFile, names[counter]);
counter++;
}
}else
cout << "Failed";
for(int counter = 0; counter < Array_Row-2; counter++)
{
for(int index = 0; index < Array_Col; index++)
{
cout << setw(4) << fixed;
cout << myScores[counter][index];
}
cout << names[counter] << endl;
}
inFile.close();
for(int counter = 0; counter < Array_Row-2; counter++)
{
cout << setprecision(2) << setw(2) << fixed;
double studentAverage = (myScores[counter][0] + myScores[counter][1] + myScores[counter][2] + myScores[counter][3])/4.0;
cout << "Student average is ";
cout << studentAverage;
cout << " ......" <<names[counter] << endl;
if(studentAverage >=90.00)
letterGrade[counter] = "A";
else if(studentAverage >=80.00 && studentAverage<=89.99)
letterGrade[counter] = "B";
else if(studentAverage >=70.00 && studentAverage<=79.99)
letterGrade[counter] = "C";
else if(studentAverage >=60.00 && studentAverage<=69.99)
letterGrade[counter] = "D";
else if(studentAverage <59)
letterGrade[counter] = "F";
cout << "Student letter grade is: "<< letterGrade[counter] << endl;
}
double classAverage = 0;
for(int counter = 0; counter < Array_Row-2; counter++)
{
classAverage += (myScores[counter][0] + myScores[counter][1] + myScores[counter][2] + myScores[counter][3]);
}
cout << "Class average is : "<< (classAverage/92.0);//calculate class average
int test1Total = 0;
for(int index = 0; index <Array_Row-2; index++)
test1Total += myScores[index][0];
int test1Average = (test1Total/23.0); //calculates test1 average
cout <<"\nStudent average for test 1: " << test1Average << setprecision(2) <<fixed;
int test2Total = 0;
for(int index = 0; index <Array_Row-2; index++)
test2Total += myScores[index][1];
int test2Average = (test2Total/23.0);
cout <<"\nStudent average for test 2: " << test2Average;//calculates test2 average
int test3Total = 0;
for(int index = 0; index <Array_Row-2; index++)
test3Total += myScores[index][2];
int test3Average = (test3Total/23.0);
cout <<"\nStudent average for test 3: " << test3Average;//calculates test3 average
int test4Total = 0;
for(int index = 0; index <Array_Row-2; index++)
test4Total += myScores[index][3];
int test4Average = (test4Total/23.0);
cout <<"\nStudent average for test 4: " << test4Average;//calculates test4 average
return 0;
}
I can't find the error you've posted, but the problem with the code is the getline(...) function.
This is getline's prototype:
istream& getline (istream& is, string& str);
as you can see it returns an istream which you cannot pass to the << operator.
What you can do is:
string str;
getline(inFile, name) >> str;
and then print:
cout << "The numbers are"
<< myArray[count][index]
<< str << endl;
You have an error in this statement
cout << "The numbers are"
<< myArray[count][index]
<< getline(inFile,name) << endl;
Operator >> performed from left to right. So first you output to cout
cout << "The numbers are"
Then you send to cout uninitialized value of myArray[count][index]
<< myArray[count][index]
And after that
<< getline(inFile,name) << endl;
Also, you have an error in using of getline. If your input file contain just space separated int values the right version is
inFile >> myArray[count][index];
cout << "The numbers are"
<< myArray[count][index] << endl;