Cout from class method does nothing

Viewed 43

I have a class "beaker" that represents a beaker with n-dices that have n-faces. It has a method "roll" which returns a vector with n-elements where each element represents a dice. Then I have another class "board" that for now, it only prints the values generated by beaker.roll using cout;

So I call the beaker.roll function to pass the result to print them, but it does nothing. I have no compile errors/IntelliSense warnings. What am I doing wrong?

#include <iostream>
#include <random>
#include <chrono>
#include <thread>
#include <vector>

using std::cout;
using std::vector;


class beaker {
    public:
        int diceCount, diceFaces;
        
        beaker() {
            diceCount = 2;
            diceFaces = 6;
        };

        beaker(int count, int faces) {
            diceCount = count;
            diceFaces = faces;
        };

        //Dice values
        vector<uint8_t> dice;

        //METHODS

        //RETURN DICE i VALUE
        int diceValue(int d) {
            return dice.at(d-1);
        }
        //ROLL DICE + RETURN RESULT
        vector<uint8_t> roll() {
            std::mt19937 mt(std::chrono::high_resolution_clock::now().time_since_epoch().count());
            std::uniform_int_distribution<int> dist(1, diceFaces);
            for (int i=0; i<diceCount; i++) {
                dice.push_back(dist(mt));
            }
            return dice;
        }       

        //RETURN LAST DICE NUMBERS
        vector<uint8_t> result() {
            return dice;
        }
};

class board {
    public:
        void Print(vector<uint8_t> dice) {
            for (int i=0; i<dice.size(); i++) {
                cout << dice.at(i);
            }
        }
};

int main() {
    beaker beaker;
    board board;
    board.Print(beaker.roll());
}
1 Answers

The problem is that the values in dice are of type uint8_t, which the cout::<< operator is interpreting as unsigned char, so it is printing out the values as ASCII characters. However, the values are between 1 and 6, and ASCII characters less than 32 are mostly non-printing characters, so they aren't visible in the output.

To convince the cout::<< operator to print the values as integers instead, update the code to this:

void Print(vector<uint8_t> dice) {
    for (int i=0; i<dice.size(); i++) {
        cout << static_cast<int>(dice.at(i));
    }
    cout << std::endl;  // just to make sure the buffer gets flushed ASAP
}
Related