Program returns imprecise results

The answers my program returns are all off by minute amounts

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
double getDistance(string fileName, string activityType, string reportType){
ifstream megaFile;
string activity;
double average=0;
string distance;
double countup=0;
double counter=0;
double distanceint;

megaFile.open(fileName.c_str());
if (megaFile.fail()){
    return 0;
}
while (!megaFile.eof( )){
getline(megaFile, activity, ',');
getline(megaFile, distance);
distanceint = atoi(distance.c_str());
if (activityType=="all"){
    countup=countup+distanceint;
    counter++;
}
else if (activityType==activity){
    countup=countup + distanceint;
    counter++;
}
else{
    return 0;
}
}
if (reportType=="avg"){
        average=countup/counter;
    return average;
}
else if(reportType=="total"){
    return countup;
}
else{
    return 0;
}
megaFile.close();
}

Here are the results- intended on the left, my program gives off the answers on the right.

5.92222 , 5.88889
53.3 , 53
2.45833 , 2.33333
14.75 , 14
1.10118 , 0.75
8.80943 , 6
3.34171 , 3.04167
76.8594 , 73
Last edited on
closed account (48T7M4Gy)
distanceint = atoi(distance.c_str());


Your problem looks like it has something to do with this conversion into an integer, which if it is, is an unusual way of reading in numerical data from a file.

Show us the whole program and a sample of the data you are using. Also it might be an idea to show exactly what you are calculating and what the numbers mean - presumably they are the output of some variable.
I'd say the use of eof() as the loop condition is a problem.

Try replacing this:
14
15
16
17
    while (!megaFile.eof( ))
    {
        getline(megaFile, activity, ',');
        getline(megaFile, distance);


with this:
14
15
    while (getline(megaFile, activity, ',') && getline(megaFile, distance)) 
    {



In the first version, even if one or both of the getline statements fail, the rest of the loop will still be executed. The second enters the body of the loop only when data has successfully been read from the file.
Last edited on
Topic archived. No new replies allowed.