C++

im trying to create a program that follows these guidelines

     read a series of integer numbers from the file “proj8.txt”
·      calculate and display the total of these numbers
·      calculate and display the average of these numbers

The number of integer numbers in the input file is unknown.
The program stops reading from the file when the end of file condition is reached

i have written the code for the first three parts but i do not know how to do the other two parts could some one please help me figure this out .
here is my code for the problem

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
      int total;
      int average;
      ofstream outputFile;
      outputFile.open("proj8.txt");

      cout << "now writing data to a file " << endl;
      outputFile << "1\n";
      outputFile << "3\n";
      outputFile << "5\n";
      outputFile << "10\n";
      outputFile << "12\n";
      outputFile << "9\n";

      outputFile.close();
      
      ifstream inFile;
      int num1;
      int num2;
      int num3;
      int num4;
      int num5;
      int num6;
      
      inFile.open("proj8.txt");
      cout << "Reading from file. " << endl;

      inFile >> num1;
      cout << num1 << endl;

      inFile >> num2;
      cout << num2 << endl;

      inFile >> num3;
      cout << num3 << endl;

      inFile >> num4;
      cout << num4 << endl;

      inFile >> num5;
      cout << num5 << endl;

      inFile >> num6;
      cout << num6 << endl;

      total = num1 + num2 + num3 + num4 + num5 + num6;
      cout << "The total of the numbers is " << total << endl;

      average = (num1 + num2 + num3 + num4 + num5 + num6) / 6;
      cout <<"The average of the numbers is " << average << endl;
      inFile.close();
      cout << "Done " << endl;
      return 0;
}//main
kajumbliesAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

w00teCommented:
while (!outputFile.eof()) {
 
}
w00teCommented:
Use a loop to read all data and sum up everything:

int count = 0;
string line;
int sum = 0;
while (!outputFile.eof()) {
    1) use getline(line, <your input stream>);
    2) convert the values from the previous line to an int.
    3) sum += the int.
    4) count++ (keep track for average);
}

your sum is already counted, and your average is sum/count.

Lookup the getline function and how to use stringstreams to convert strings to integers.  There's a few nice solutions on this website for stringstreams including an article which desribes multiple ways to do this convertion.

Good luck,

w00te
itsmeandnobodyelseCommented:
>>>> The number of integer numbers in the input file is unknown.

Because of that you need a loop, e. g.

int total = 0;
int num = 0;
while (inFile >> num)
{
    ...
}
inFile.close();

The loop above would end on eof or on fail.

Instead of ... simply add the num currently read to the total.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

jkrCommented:
Take a look at http://www.cplusplus.com/doc/tutorial/control/ ("Control Structures"), especially the part that is titled "Iteration structures (loops)" as w00te has mentioned. Then, ask yourself if you really need one variable per number you are reading or if one is enough for your task. Hm, what else would you need? Another variable to sum up the input and one that counts the amount of numbers read maybe?
w00teCommented:
I tried to limit my solution so he'd have to research things and it wouldnt violate the academic rules (pretty obviously a school question), but feel free to delete it if it matters.  Just wrote it in 30 seconds on a coffee break so I really wouldn't mind :)
-w00te
evilrixSenior Software Engineer (Avast)Commented:
w00te, your post is fine :)
kajumbliesAuthor Commented:
well I never asked for the entire solution I asked for help figuring out how to approach the last two parts of the question I wanted some help so that I ould understand and get the answer on my own
jkrCommented:
Well, then follow the hints that you've got so far ;o)
kajumbliesAuthor Commented:
w00te what you said is really helpful I know how to figure out how get the progeam to count the numbers however I'm still struggling with getting the total and the average
jkrCommented:
Think along these lines again: Ask yourself if you really need one variable per number you are reading or if one is enough for your task. Hm, what else would you need? Another variable to sum up the input and one that counts the amount of numbers read maybe?
w00teCommented:
Correction for my first post -- should be !infile.eof() and the value in <> should be infile as well (the same stream). My bad :) you can also read a single value instead of using getline and stringstreams as everyone else showed with infile>>Someintegervar.
kajumbliesAuthor Commented:
here is what i have i can get it to read the number but i now cant figure out how to total the bnumbers up and average them  this is really confusing

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
      int total;
      int average;
      ofstream outputFile;
      outputFile.open("proj8.txt");

      cout << "now writing data to a file " << endl;
      outputFile << "1\n";
      outputFile << "3\n";
      outputFile << "5\n";
      outputFile << "10\n";
      outputFile << "12\n";
      outputFile << "9\n";

      outputFile.close();
      
      ifstream inFile;
      int num;
      /*int num1;
      int num2;
      int num3;
      int num4;
      int num5;
      int num6;*/
      int count;
      
      inFile.open("proj8.txt");
      cout << "Reading from file. " << endl;
      
      count = 0;
      inFile >> num;
      cout << num << endl;
      ++count;

      inFile >> num;
      cout << num << endl;
      ++count;
      inFile >> num;
      cout << num << endl;
      ++count;

      inFile >> num;
      cout << num << endl;
      ++count;
      inFile >> num;
      cout << num << endl;
      ++count;
      inFile >> num;
      cout << num << endl;
      ++count;
      cout << "The number of numbers in the file is " << count << endl;
      
      cout << "The total of the numbers is " << endl;

      
      cout <<"The average of the numbers is " << endl;
      inFile.close();
      cout << "Done " << endl;
      return 0;
}//main
kajumbliesAuthor Commented:
i dont know how to impliment the getline function to complete this program can someone please help expalin what i need to do
kajumbliesAuthor Commented:
yes i have i guess i just have a hard time understanding how to impliment loops and how to make this thing work properly
in the line

int n = read int from line in file(); do i put in perentheses the name of my file

iv broken this thing down so many times i just dont get how to impliment the code to  make this work
w00teCommented:
I don't want this to sound bad, but where are you getting this question? You must have class notes or a textbook that covered these things (whether your at school or teaching yourself). You shouldn't be trying to read files if you don't even understand basic statement syntax.  It's like trying to cook when you don't even know the ingredients you need.

Cplusplus.com has good intro tutorials, spend an hour reading them and then try, it'll save you alot of time in the end -- trust me.
kajumbliesAuthor Commented:
well i understand how to read a file i just dont get how to put it into a loop and then make it add up number with only one variable its just confusing
itsmeandnobodyelseCommented:
>>>> i dont know how to impliment the getline function to complete this program can someone please help expalin what i need to do

The getline function is to read a line of *text* into a *string*.

   string line;
   getline(inFile, line);

The problem that arises with getline for your requirements is that you need numbers (int type) and not strings in order to calculate the average. You could solve that by *converting* the text to a number:

   int num = atoi(line.c_str());  

Here the c_str returns a const char* from the string type. That is a zero-terminated char array (e. g. "123\0"  . The \0 is opposite to '0' a binary zero character).

Your current code is not using getline (and strings) but reads directly to an int:

     int num;
     inFile >> num;

That is fine as long as there is no garbage in the text file. If for example there would be a line with "xyz\n" the inFile >> num would *die* on that xyz and the inFile goes to fail state.

>>>> i understand how to read a file i just dont get how to put it into a loop

There are three kind of loops:

  (A) the for loop

  for (int i = 0; i < maxnum; ++i)
  {
      ...
  }

  (B) the while loop

    int i = 0;
   while (i < maxnum)
   {
         i++;   // important: you must do some action in the loop that it could end somehow
         ...
   }

  (C) the do while loop

   int i = maxnum;
   do
   {
        i--;   // same applies here
        ...
   } while (i >= 0);

The difference between (B) and (C) is that the C loop was invoked at least once.

Note, the condition in the while loops or in the middle of the for statement can be any expression that could be tested on 'true' or 'false'. For example, if you read from file using

    inFile >> num

you could use the (inFile >> num)  as the loop condition. That is because

    inFile >> num

would return a NULL (== 0 == false) in case the read fails. Same is for getline:

   while (getline(inFile, line))
   {
       ....
   }

is a well-defined loop which will break at end-of-file and when an error occurs.

You could use any of the three loop types though normally (B) is the choice for reading files where you don't know how many lines it has (i. e. the 'maxnum' is unknown). On the other hand, the for loop has the advantage that it automatically can manage a counter. You would need that counter cause you have to calculate the average which is defined as total (sum) divided by the count (of numbers).

When using (B) or (C) you would need to provide such a counter yourself:

    int count = 0;
    while (<some_condition>)
    {
           count++;    // here we manage the counter
           ...
    }

When using (A) you would have

     int count;
     for (count = 0;  <some_condition>; ++count)  // would increment after each loop cycle
     {
           ....
     }

what is equivalent to that before.

>>>> and then make it add up number with only one variable

You have two variables defined before the loop. One is the 'total' which is 0 initially. In the loop you have to add the number currently read from file. The second is the count which also is 0 and must be incremented by 1 for each loop cycle. After the loop you need a double (floating point number) in case you want to get the average as a decimal number and not only as an integer (rounded down).
 
phoffric\Commented:
>> then make it add up number with only one variable
I think you misunderstood the advice give. You can use as many variables as you need to handle each of the problem parts.

You already have a link on control structures that explains how to do while loops and for loops. You already have been told how to know when you hit the eof (first post). So, at a minimum, you should try to take that information and attempt to show a loop. Presumably your book has a simple example showing how to do this. Here is a link from the recommended tutorial page that has a loop while reading a file:
     http://www.cplusplus.com/doc/tutorial/files/
Just start copying code snippets from tutorials, and try them out until you understand them. (If you have trouble understanding a tutorial, then you can ask another specific question about the tutorial (and give the link).

Now, without writing a computer program...
If I give you a partial deck of cards (but I don't tell you how many cards there are), could you look at one card at a time do the following:
  -- a. Turn over one card at a time and after noticing the value, throw away that card
  -- b.        other steps to be supplied by you
  -- c. Obviously, stop trying to turn over cards if the pile is empty
  -- d. After the pile is empty, tell me:
     1) what is the sum of the values on the cards (assume J, Q, K, A count as 11, 12, 13, 1)
     2) what is the average of the values on the cards

As an example, if I give you a pile, and you find there are two cards: 2 and 3
Then the sum is 5 and the average is 2.5

Now, I assume that you can do this intuitively. To make it less intuitive, suppose I have 100 decks of cards, and I can give you anywhere from 1 to 5200 cards. Let's say I give you a pile of 3751 cards in it. But you didn't know that there were 3751 cards in it when you looked at the pile.

So, using a paper and pencil, tell me all the steps you do (but don't list 3751 steps!) so that you know the total and the average after turning over one card at a time, and then throwing away that card (i.e., you will not be able to see that card again after it is thrown away).

Generally, when I get stumped in figuring out how to write a program, I get a paper and pencil, and yes, sometimes a deck of cards, and I first figure out how to do it by hand. I always start off with maybe a couple of items just to get a feel for solving the problem. But then when I add many items to the list, I often find that the first simple approach needs to be enhanced a little.

Then I may do it yet again, one more time with a different set and size of items just to make sure that the previous approach still works for a new set of input values. Then I use the syntax of the programming language to mimic what I did by hand.

Let's give this a try. Fill in the non-computer steps that go in step b in the above list.
w00teCommented:


Okay,

If all you don't get is the loop, it works like this:

There are 2 basic loops you need to be aware of, the first is a for loop (ignore that, you're not using it -- look it up somewhere later though!), and the second is a while loop.  You're obviously using a while loop.

While loops keep doing the same set of instructions over and over until their condition is not met.  So, for example:

bool x = true;
while (x) {
 
}
w00teCommented:
Beh sorry, pressed the wrong key.

bool x = true;
while(x) {
    cout<<"ran loop."<<endl;
    x = false;
}

This will print "ran loop" once because when we get to the loop x is true (so basically) but during the loop x is set to false.  The value in the () part of the while loop always evaluates to true or false.  If it ends up being true, then we do the code in the loop, and if its false we are done with the loop and move on to the code after the } at the end of the while loop.

So, something more compliated:

it x = 0;
while (x < 10) {
    cout<<"ran loop.";
    x = x + 1;
}

This will print "ran loop" 10 times because it will keep repeating the code inside the { } of the loop until x < 10 is false.  Since x starts at 0 and gets incremented once every time the code is run, it runs 10 times before the condition x < 10 evaluates to false and the loop is complete.

Now, here's the last part you need to know.

When you are reading your file you're using the

while( ! infile.eof() ) {
    //Your code.
}

layout.  The eof() part is a function that means end of file.  So, when you put infile.eof() you're checking if the file you're reading (called infile, its an ifstream), has reached the end.  If you haven't reached the end this function returns true, and your program executes the code you place inside where I've written "//Your code".  If you have read the last integer and you're at the end fo the file, infile.eof() evaluates to false and you're loop stops running and your program continues after the last } in the loop.

One more thing to note:

infile.eof() actually checks to see if you're at the end of the file -- it will return true when the end of file is reached while you actually want it to return false in order to close the loop when the end of file is reached.  The ! in !infile.eof() means NOT and it reverses the value returned by the function.  So, in your case when we haven't reached the end of file !infile.eof() returns true (making the code in the loop run again), and when we have reached the end of file !infile.eof() returns false and the loop stops running and the program continues after it.

Hope this solved your confusion, and best of luck to you.

-w00te
itsmeandnobodyelseCommented:
>>>> !infile.eof()

You better test on (infile) and not only on !infile.eof().

The (infile) condition will be false not only on eof but also if you encounter an error while reading the file. So that is not much likely it could happen and it would cause your loop to run infinite cause the eof condition never would go true.

As already told above you could test an istream like a pointer (which is baseclass of ifstream) cause the operation would return NULL (what also means false) in case the istream is not in 'good' state. That is true for eof and fail state.

    // wouldn't go into loop if you had an open error
    while (inFile)
    {
          // next statement could change state of inFile
          inFile >> num;

or shorter
 
    while (inFile >> num)
    {
           ...
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.