Simple error.

We was asked to create a program using a class called CounterType that counted things. Then we had to create a program using 3 CounterTypes, one for positive Numbers, Negative Numbers, and Zeroes. It reads in data from a text file which we customize the numbers to make sure it works. We have the program near perfect, with one fault. It adds an extra count to whatever the last digit of the text file is. For example if it ends in Negative, it adds an extra count to the negative counter.

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <fstream>
using namespace std;

class CounterType
{
 public:
        void plus();
        void nega();
        void display();
        CounterType( )
         {
          counter = 0;
         }

        CounterType(int count)
         {
          counter = count;
         }

 private:
        int counter;

};

void CounterType::plus()
{
  counter++;
}

void CounterType::nega()
{
 if(counter == 0)
  {
   cout << "ERROR: Counter cannot become negative\n";
  }

 else
  {
  counter--;
  }

}

void CounterType::display()
{
        cout << counter << endl;

}

int main()
{
 int num;
 ifstream file1;
 file1.open("num.txt");
 CounterType positive;
 CounterType negative;
 CounterType zeroes;

while(file1)
  {
   file1 >> num;
   if(num > 0)
   {
    positive.plus();
   }
   else if(num < 0)
   {
    negative.plus();
   }
   else if(num == 0)
   {
    zeroes.plus();
   }
   else;

  }

 cout << "Positives:";
 positive.display();
 cout << "Negatives:";
 negative.display();
 cout << "Zeroes:";
 zeroes.display();
 return 0;
}
Still looking for some help, thanks!
1
2
3
4
5
6
  while(file1)
  {
   file1 >> num;
   if(num > 0)
   {
    positive.plus();


should be:

1
2
3
4
5
  while(file1 >> num)
  {
   if(num > 0)
   {
    positive.plus();


You usually want to see if the input extraction is successful, not check the state of the file prior to an extraction attempt and then just assume the extraction was successful.
Last edited on
Topic archived. No new replies allowed.