C++ That Is Plaguing Me To This Day - c++

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

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.

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

Exercise: for cycle and array

I have to write a program that allows to calculate the arithmetic average of an arbitrary numbers of values (chosen by the user)
It will outputs:
Number: 34
Number: 36
Number: 44
Number: //and I choose to stop input pressing
//Outputs:
It was inserted 3 numbers and the avarage is: 38
Of course i've forgot to post what i've done:
for (int x = 0; x < 50; x++){
cout << "Number: ";
cin >> number[x];
cout << "You have inserted the " << x << " element of the array;" << endl;
sum += number[x];
avarage = sum / number[x];
nEelementi = number[x];}
so I run the program, input some numbers, press something like ctrl+d or trying to add something to the code.. but it only goes from the first to the last element of the array with no values, becouse not entered, of course.. and then print absurd avarage and sum.
I know I don't need an array to do this but it's required from the exercise.. also the exercise only request to use for or while loop and arrays.
What I need is a way to stop the input and calculate the sum and avarage of only what I wrote.
edit1.
I've tried to dived by n writing for(x = 0; x < n, x++) because it made sense to me, but i think it "thinks" n, wrote like this, infinite, because the results is 0 (because the limit of a number divided by infinite is 0).. so i've started becoming mad.
Now i've started thinking that it would be easier to use while loop! and wrote
#include <iostream>
using namespace std;
int main() {
int num[50];
double sum = 0;
double average = 0;
int cont;
int end = 0;
while (cont < 50) {
cout << "num: ";
cin >> num[cont];
sum += num[cont];
cont++;
cout << "Want to continue 0 = sì, 1 = no";
cin >> end;
if (end == 1) {break;}
}
average = sum / cont;
cout << "You have insert " << cont << " elements" << endl;
cout << "LThe sum is: " << sum << endl;
cout << "The avarage is: " << average << endl;
return 0;
}
BUT still doesn't work. My professor says you should be able to stop input number by pressing ctrl+d so I'm not doing good.
Sorry for late answer but i have also to translate the code.. hope all translation is good:)
edit2.
#include <iostream>
int main() {
int sum = 0;
int num;
while ( std::cin ) {
std::cout << "Number: ";
std::cin >> num;
}
if ( std::cin >> num ) {
sum += num;
num++;
}
else {
std::cin.clear();
std::cout << "Input interrupted" << std::endl;
}
std::cout << "Sum is " << sum << std::endl;
std::cout << "You have entered " << num << " numbers" << std::endl;
return 0;
}
I love this new code, very simple and understandable to me, but I was not able to add sum operation, it only outputs 0! (leaving out average)
And also I was not able to determinate, and display, how many numbers I've entered. The last row of the code is just an example of what I want to do..
edit3.
Finally I made it.
#include <iostream>
using namespace std;
int main(){
double numero;
int index = 0;
double somma = 0.;
cout << "Inserire un numero: ";
while( cin )
{
if ( cin >> numero )
{
somma = somma + numero;
index++;
cout << "Inserire un numero: ";
}
else
{
cout << "Input interrotto" << endl;
}
}
cout << "Sono stati inseriti " << index << " numeri e la lora media è:
<< somma / index << endl;
return 0;
}
Thanks so much!
P.S. To the end, I don't need to use an array, it's just simple
There are a few problems here. One is that if the stream errors due to being closed or bad input, you don't recover and you just charge through your loop.
So first, make the loop terminate early if necessary. I'm also going to convert it to a while loop in preparation for the next part.
int x = 0;
while( std::cin && x < 50 )
{
std::cin >> number[x++];
}
Now it terminates early if the stream errors. But what if the user typed in "hello"? You could ignore it and continue like this:
if( std::cin >> number[x] )
{
x++;
}
else
{
std::cin.clear();
}
Notice that I didn't compute the sum or anything inside the loop. There's no need, since you are already putting them in an array. You can just do it after the loop. Here, I'm using std::accumulate
double sum = std::accumulate( number, number + x, 0.0 );
double average = 0.0;
if( x > 0 ) average = sum / x;
Now, you have also said you want an arbitrary number of values. Your original code allowed up to 50. Instead of storing them, you can instead just compute on the fly and discard the values.
double sum = 0.0;
int count = 0;
while( std::cin )
{
double value;
if( std::cin >> value )
{
sum += value;
count++;
}
else
{
std::cin.clear();
}
}
double average = 0.0;
if( count > 0 ) average = sum / count;
If you still want to store the values along the way, you can use a vector.
std::vector<double> numbers;
//...
numbers.push_back( value );
And if you want the user to choose the number of values:
std::cout << "Enter number of values: " << std::flush;
std::size_t max_count = 0;
std::cin >> max_count;
std::vector<double> numbers;
numbers.reserve( max_count );
while( std::cin && numbers.size() < max_count )
{
// ...
}

Using functions properly

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.