input, output, sum problem.

Hello everyone. I am new to C++ programming, and am in need of serious help. This is a HW assisgnment I'm not going to lie. It's actually a big project:(
So I have to take a user name and a file name as input from the keyboard. Then the program needs to open the file and find the mean (or average) of all the values in the file. The program should ignore all non-numeric input in the file (a tough one). The program should write the user name and the mean to a new file enclosed in asterisks, followed by all the valid input from the input file. This problem should be solved without using an array or other method of storing all the values in memory.
From reading the first half of my book (where we are in the class) I've seen a lot of examples but knowing what symbols and {} go where. let alone getting the correct info from the file. I dont even know where to start.
Any help would be greatly apprecaited. this is what I have so far (please dont laugh):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
    ifstream inData;
    ofstream outData;
    string firstName;
    int counter;
    int num;
    int sum = 0;
    char fileName[80];

    cout << "Enter your name: " << endl;
    cin >> firstName;

    cout << "Enter the file name: " << endl;
    cin >> fileName;
    
    inData.open (fileName);
 if (!inData)
 {
    cout << "Cannot locate file! " << endl;
    return 1;
 }
  
  
  inData >> num;
  while (num != )
 {
     sum = sum + num;
     inData >> num;
 }  


   
    inData.close();
    outData.close();

return 0;
}
It's actually not a bad start IMO. For your while loop, change it to loop until you detect end of file on inData:

1
2
3
4
5

while( inData.good() )
    {
    }    /*    while( inData.good() )    */


Read your input into a string:

1
2
3
4
5

string aString = "";

inData >> aString;


You could check num to see if it is numeric by using atoi():

1
2
3
4
5
6
7

    num = atoi( aString.data() );

    if( num != 0 )
        sum += num;




Give that a whirl ...
Thanks for the help. It's really starting to look like a real program now:) It compiled great, now just one bug. when it ask's for file name it pauses. I should be able to debug from here! again thanks so much for the help!Your a Life saver kooth!!!
Thanks for the kind words, AKAMacC, but I consider myself more of a lemon drop. ;)

Good luck!
cin >> does not like character arrays... I suggest looking into getline()... There are two versions. Search and find the one that works best for you.
Last edited on
Topic archived. No new replies allowed.