Calculating a sum with two variables from a user-created output file

I am trying to figure out exactly how I am using my output text file that I created to use to calculate the sums of both variables. My output text file stores the information correctly, but I am getting 0s and 0s for my sums so that it doesn't read the information I guess. Also, is the information I enter into the arrays only saved in the text file? I need it to be stored in a text file only, so that sum calculations only get 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;
}

      

+3


source to share


1 answer


At the end of the first cycle:

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 wrong, so the body of the loop will never be executed.

For this to work, you will need to reset back to zero for it to view the items again. Or better yet, leave it alone count

(since it indicates how many elements were processed) and use another variable to step through them:

for (int i = 0; i < count; ++i) { ... use i rather than count ... }

      

0


source







All Articles