while and if statements... not sure how to loop. If you could be of any help that would be amazing!

In this code I am trying to write a code that will count the number of 0's and the number of 1's from a ifstream...
My result should look like this:
Sample contents of digital.dat:
1 0 0 0 0 1 1 0 1 0 1 1 1 1 0 0 0 1

Message to be displayed:
Emit 1270-hz tone for 1 time units
Emit 1070-hz tone for 4 time units
Emit 1270-hz tone for 2 time units
Emit 1070-hz tone for 1 time units
Emit 1270-hz tone for 1 time units
Emit 1070-hz tone for 1 time units
Emit 1270-hz tone for 4 time units
Emit 1070-hz tone for 3 time units
Emit 1270-hz tone for 1 time units

Here is my current code:
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
int digit;
int count = 1;
ifstream indata;
indata.open("digital.txt");
indata >> digit;
if(digit = '1')
{
count = digit;
cout << "Emit 1270 for" << count << "times." << endl;
indata >> digit;
count++;
}
else if(digit = ('0')
{
count = digit;
cout << "Emit 1070 for " << count << "times." << endl;
indata >> digit;
count++;
}
return 0;
}
I can see what you are trying do, but this is basic file mechanics.

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
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
      
      int lastDidgit = -1; // I set to -1 because of the possibility that the file can start with 0.
      int currentDidgit;
      int count =0;
      ifstream indata;

      indata.open("digital.txt");
      if(indata.good())  // see if we got the file open correctly
      {
           // now loop throught the file to the end. eof stands for end of file.
           while(indata.eof() != true)
           {
                 // read in the next didgit
                 indata >> currentDidget;
                        
                 // see if its the same as lastDidgit
                 if(currentDidget != lastDidgit)
                 {
                        // output info
                        cout << "Emit 1270 for" << count << "times." << endl;
                       // reset the count.
                        count = 0;
                 }
                 else
                 {
                        count++;
                 }

                 // set the lastDidgit for the next pass of the loop
                 lastDidgit = currentDidgit;

           } // end of while
      }
      else // for a good file
      {
            cout << "Could not open Input stream for some reason!" << endl;
      }
      return 0;
}


I hope this points you in the right direction.
Last edited on
Thanks helped a lot!!!
Thanks for sharing Azagaros. This was also my issue with my project but it is now working properly.
Topic archived. No new replies allowed.