Trying to count occurrences of number 3...it's a little off.

Pages: 12
does that work with .bin binary files? I'm just getting a "cannot open" message.
closed account (48T7M4Gy)
@OP,
Why dont you do it another way and make up your own binary file of ints (32 bit ints) with a known number of 3's Just use a random number generator in a loop and count the 3's as they are filed.

Then once you have that run your test program and check the result.

All of that is a simple couple pf lines modification to the sample I posted above.

closed account (48T7M4Gy)
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
#include <iostream>
#include <fstream>

#include <ctime>

int main()
{
    // *** OUTPUT TO A BINARY FILE ***
    //std::cout << "Please enter output file name: ";
    std::string oname = "binary_input_output_count.bin";
    //std::cin >> oname;
    
    std::ofstream ofs{oname,std::ios_base::binary};
    if (!ofs) std::cout << "Can't open output file " << oname << '\n';
    
    size_t count = 0;
    uint32_t number = 0;
    
    srand (time(nullptr));
    
    for(int  i = 1; i < 1'000'000; ++i)
    {
        number = rand() % 10;
        
        if(number == 3){ count++ ; }
        ofs.write(reinterpret_cast<char*>(&number), sizeof number);
    }
    ofs.close();
    
    
    
    // *** INPUT FROM A FILE ***
    //std::cout << "Please enter input file name: ";
    std::string iname = "binary_input_output_count.bin";
    //std::cin >> iname;
    
    std::ifstream ifs {iname, std::ios_base::binary};
    if (!ifs) std::cout << "Error - can't open input file " << iname << '\n';
    
    // READ THE DATA FROM THE BINARY FILE AND CHECK CONTENTS AGAINST target
    uint32_t aNumber = 0;
    double target = 3;
    size_t no_3s = 0;
    
    while( ifs.read(reinterpret_cast<char*>(&aNumber), sizeof aNumber) )
    {
        //std::cout << "Number is: " << aNumber;
        if(aNumber == target)
        {
            //std::cout << " *** BINGO! ***";
            no_3s++;
        }
        //std::cout << '\n';
    }
    std::cout << "  No. of 3's generated: " << count  << '\n';
    std::cout << "No. of 3's encountered: " << no_3s  << '\n';
    
    ofs.close();
    
    return 0;
}


No. of 3's generated: 99965
No. of 3's encountered: 99965
Program ended with exit code: 0
Topic archived. No new replies allowed.
Pages: 12