calculating a sum with two variables from user created output file - c++

I'm trying to figure out how exactly I'd use my output text file I created to be used to calculate the sums of both variables. My output text file is saving the information correctly, but I get 0 and 0 for my sums so it's not reading the information I think. Also, does the information I enter into the arrays only save into the text file? I need it only being saved into the text file so that the sum calculations are only receiving information from the text file
#include <iostream>
#include <string>
#include<iomanip>
#include <fstream>
using namespace std;
int main() {
int ItemNumber[2];
float price[2];
int sumnumber = 0;
float sumprice = 0;
string myfile = "c:/Users/rz/Desktop/numbers.txt";
int count = 0;
ofstream outFile;
outFile.open(myfile);
while (count <= 1)
{
cout << "enter a price" << endl;
cin >> price[count];
outFile << price[count] << endl;
cout << "enter a item number" << endl;
cin >> ItemNumber[count];
outFile << ItemNumber[count] << endl;
count++;
}
outFile.close();
fstream inFile;
inFile.open(myfile);
while (count <= 1)
{
sumprice = sumprice + price[count];
sumnumber = sumnumber + ItemNumber[count];
}
cout << sumnumber << endl;
cout << sumprice << endl;
system("pause");
return 0;
}

At the end of the first loop:
int count = 0;
while (count <= 1) { ... count++ ... }
the variable count will be set to 2.
Then, when you start the second loop:
while (count <= 1) ...
the condition is already false, hence the body of the loop will never be executed.
In order for this to work, you would have to reset count back to zero so that it runs through the items again. Or, better yet, leave count alone (since it indicates how many items were processed) and use another variable to got through them:
for (int i = 0; i < count; ++i) { ... use i rather than count ... }

Related

How to create multiple text files, and for loop matrixes that iterate over rows first and columns second

So, I'm currently programming for a computational linear algebra class, and I seek some guidance on how to create the proper code for an assignment. I have 2 problems, with the first being that I can't generate a second txt file with my code, and the second possibly being on how exactly I can make this second matrix iterate through its rows first, with the columns being second rather than the traditional columns first, rows second format.
My main issue is trying to implement the second txt file, where I've tried using both outfile(which I assume is the only proper way), as well as my own variation of outfile2. Neither presents a new txt file, and there's no error message either so...
Here is my tried code:
// Base Coder Package
#include <iostream>
// File Creator Package
#include <fstream>
using namespace std;
// The purpose of this program is to print out a matrix whilst utilizing the
// Appropriate methods
int main()
{
// Mat1 Matrix
num = 1;
// Parameter for output to file
ofstream outfile;
outfile.open("jsimonoff_p1_mat1.txt");
if (outfile.is_open())
{
// Prints the number of rows for my last name = 8
for (int i = 1; i <= 8; i++)
{
// Prints the number of columns for my first name = 7
for (int j = 1; j <= 7; j++)
{
// Formats the Matrix
if (num <= 9)
{
// Increments by one after printing a number
outfile << num << " ";
num++;
}
else
{
outfile << num << " ";
num++;
}
}
outfile << endl;
}
// Close the file
outfile.close();
}
else
{
cout << "Error, file not opened.\n";
}
// Mat2 Matrix
ofstream outfile2;
int num2 = 3;
outfile2.open("jsimonoff_p1_mat2.txt");
if (outfile2.is_open())
{
// Prints the number of columns for my last name = 8
for (int j = 1; j <= 8; j++)
{
// Prints the number of rows for my first name = 7
for (int i = 1; i <= 7; i++)
{
// Formats the Matrix
if (num2 <= 9)
{
// Increments by one after printing a number
outfile2 << num2 << " ";
num2 += 5;
}
else
{
outfile2 << num << " ";
num2 += 5;
}
}
outfile2 << endl;
}
// Close the file
outfile2.close();
}
else
{
cout << "Error, file not opened.\n";
}
return 0;
}
As far as I'm aware, this question seems unique.

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!

Returning garbage numbers and I don't know why

I'm trying to create a program that reads in numbers from a file into an array, reverse the order of the numbers in the array and then outputs those reversed numbers into a different file. I was able to get the program to work when I already knew how many numbers were in the file but I am having difficulty when I switch my loop to trying to detect the EOF(End of file). When I run this code it will print two of the numbers from the file and the rest are garbage values. Any Help?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int NUMS = 5;
void reverseArray(int number[], int first, int last)
{
int temp;
if (first >= last)
{
return;
}
temp = number[first];
number[first] = number[last];
number[last] = temp;
reverseArray(number, first + 1, last - 1);
}
int main()
{
//Create file objects
ifstream inputFile;
ofstream outputFile;
string inputName;
string outputName;
//Prompt user for file names
cout << "What is the name of the input file?" << endl;
getline(cin, inputName);
cout << "What would you like the output file to be called?" << endl;
getline(cin, outputName);
//open user named files
inputFile.open(inputName);
outputFile.open(outputName);
int numsFromFile;
int numbers[NUMS];
int fileCount = 0;
/*
//read in numbers from a file ********THIS WORKS BUT WHEN I CHANGE IT BELOW IT DOES NOT******
for (int count = 0; count < NUMS; count++)
{
inputFile >> number[count];
}
*/
//Try to read numbers in detecting the EOF
while (inputFile >> numsFromFile)
{
inputFile >> numbers[fileCount];
fileCount++;
}
//print numbers to screen
for (int count = 0; count < fileCount; count++)
{
cout << numbers[count] << endl;
}
//reverse array
reverseArray(numbers, 0, 4);
cout << "Reversed is: " << endl;
//print reversed array
for (int count = 0; count < NUMS; count++)
{
cout << numbers[count] << endl;
}
//output numbers to a file
for (int count = 0; count < NUMS; count++)
{
outputFile << numbers[count] << endl;
}
outputFile.close();
inputFile.close();
return 0;
}
There is a bug in the lines:
while (inputFile >> numsFromFile)
{
inputFile >> numbers[fileCount];
fileCount++;
}
You end up reading and discarding the 1st number, the 3rd number, the 5th number, etc. Change it to:
while (inputFile >> numsFromFile)
{
numbers[fileCount] = numsFromFile;
fileCount++;
}

ifstream runtime error when attempting to save the data into array

I'm having a problem when I try to read the external text file.
The displayed text is correct but when it comes to saving the data into an array, it seems to be wrong.
My input numbers are 4 2 8 0 2 3 0 4 0 5, but after looping through the array, a[i], only '48' appears.
#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
void begin ();
void Process (string);
using namespace std;
int main()
{
begin();
system("pause");
return 0;
}
void begin (void){
string file = "data.txt";
Process(file);
}
void Process (string file)
{
int i=0,ch, n = 0, temp, a[50];
ifstream infile;
infile.open(file.c_str());
The error seems to be caused from here.
if(infile.is_open())
{
cout << "File to be read: " << file << endl;
cout << "\n\n";
infile >> temp;
while(!infile.fail())
{
cout << temp << " ";
infile >> temp;
a[i] = temp;
i++;
n++;
}
cout << "\n\n";
cout << "This file has " << n << " numbers. \n\n";
}
else
cout << "The file isn't available! \n\n";
infile.close();
When I try to output the result, only 48 appears.
for (int z = 0; z < i; z++)
{
cout << a[i] << endl;
}
}
I'm new here. Please help. Thanks in advance.
Your display loop is using i instead of z to index into a (this should be a good lesson on why variable naming is important!) Change your display loop to this:
for (int z = 0; z < i; z++)
{
cout << a[z] << endl;
}
There are potentially more issues with your code, but this seems to be what is blocking you. Consider renaming i and a to more meaningful things. The time you will spend typing will always be dwarfed by the time you spend trying to understand what you meant.
Consider this loop
for (int z = 0; z < i; z++)
{
cout << a[i] << endl;
}
You always output one element a[i] instead of a[z]. Moreover element with index i was not assigned. The last assigned element is a[i-1].
Apart from this you do not save the first entered number in the array. You start to save entered data from the second number.
infile >> temp; // <== this value was not assigned to an element of the array
while(!infile.fail())
{
cout << temp << " ";
infile >> temp;
a[i] = temp;
Also this statement inside the loop
infile >> temp;
can result in error. So after that there is no sense to write
a[i] = temp;
because nothing was entered and in fact you will store the previous number in the next element.

Difficulty analyzing text from a file

I'm running into a rather amusing error with my output on this lab and I was wondering if any of you might be able to hint at where my problem lies.
The goal is find the high, low, average, sum of the record, and output original record.
I started with a rather basic program to solve for one record and when I achieved this I expanded the program to work with the entire text file. Initially the program would correctly output:
346 130 982 90 656 117 595 High# Low# Sum# Average#
When I expanded it to work for the entire record my output stopped working how I had wanted it to.
0 0 0 0 0 0 0 High: 0 Low: 0 Sum: 0 Average: 0
0 0 0 0 0 0 0 High: 0 Low: 0 Sum: 0 Average: 0
etc...
I cant quite figure out why my ifstream just completely stopped bothering to input the values from file.
I'll go take a walk and take another crack at it. If that doesn't work I'll be back here to check for any responses =)
Thank you!
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int num;
int high = 0;
int low = 1000;
double average = 0;
double sum = 0;
int numcount = 0;
int lines = 1;
char endoline;
ifstream inData;
ofstream outData;
inData.open("c:\\Users\\Nikko\\Desktop\\record5ain.txt");
outData.open("c:\\Users\\Nikko\\Desktop\\record5aout.txt");
if(!inData) //Reminds me to change path names when working on different computers.
{
cout << "Could not open file, program will exit" << endl;
exit(1);
}
while(inData.get(endoline))
{
if(endoline == '\n')
lines++;
}
for(int A = 0; A < lines; A++)
{
for(int B = 0; B < 7; B++)
{
while(inData >> num)
inData >> num;
numcount++;
sum += num;
if(num < low)
low = num;
if(num > high)
high = num;
average = sum / numcount;
outData << num << '\t';
}
outData << "High: " << high << " " << "Low: " << low << " " << "Sum: " << sum << " " << "Average: " << average << endl;
}
inData.close();
outData.close();
return(0);
}
In the inner loop you read until the stream enters failure-mode, e.g., because an incorrect format was received or the stream reached its end. Once the stream entered failure-mode it will stay in this mode until the error flag is used, e.g., using inData.clear(). I don't know how your input looks but assuming it is a file consisting entirely of numbers, it will just read the entire file. If you want to break out of reading earlier, you need to do something about. For example, you could use a manipulator to skip over whitespace and set the stream into a failure state when reaching a newline:
std::istream& skip(std::istream& in) {
std::istream::sentry cerberos(in, false);
if (in) {
while (std::isspace(in.peek()) {
if (in.get() == '\n') {
std::in.setstate(std::ios_base::failbit);
}
}
}
}
... later, when reading integers use this:
int value(0);
while (in >> skip >> value) {
// ...
}
// ...
if (!in.eof()) {
in.clear();
}
When skip encounters a newline, the stream is set into failure-mode as a record (line) was read. After processing the line, the stream state is cleared unless the failure was due to also reaching EOF which would set the std::ios_base::eofbit which is tested using in.eof().
I think you have too many cycles :)
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int num;
int high = 0;
int low = 1000;
double average = 0;
double sum = 0;
int numcount = 0;
int lines = 1;
char endoline;
ifstream inData;
ofstream outData;
inData.open("c:\\Users\\Nikko\\Desktop\\record5ain.txt");
outData.open("c:\\Users\\Nikko\\Desktop\\record5aout.txt");
if(!inData) //Reminds me to change path names when working on different computers.
{
cout << "Could not open file, program will exit" << endl;
exit(1);
}
while(inData.get(endoline))
{
if(endoline == '\n')
lines++;
sum = 0;
average = 0.;
high = 0;
low = 1000;
//you have to reinitialize these values for every row
while(inData >> num)
{
numcount++;
sum += num;
if(num < low)
low = num;
if(num > high)
high = num;
average = sum / numcount;
outData << num << '\t';
}
outData << "High: " << high << " " << "Low: " << low << " " << "Sum: " << sum << " " << "Average: " << average << endl;
}
inData.close();
outData.close();
return(0);
}
Thank you both for taking the time to help me out with this. I borrowed bits from both of your responses.
After my first while loop I added in inData.clear(); & inData.seekg(0);. Adding these stopped my inData >> num from being filled with -858993460.
I also removed the pesky while(inData >> num) and simply replaced it with inData >> num;
Lastly, I set the variables that would need to be reinitialized to 0 inside the first for loop.