c++ - 来自类方法的 Cout 不执行任何操作

标签 c++ class vector methods cout

我有一个“烧杯”类,它代表一个带有 n 个面的 n 个骰子的烧杯。它有一个方法“roll”,它返回一个包含 n 个元素的 vector ,其中每个元素代表一个骰子。然后我有另一个类“board”,目前它仅使用 cout 打印 beaker.roll 生成的值;

所以我调用 beaker.roll 函数来传递结果来打印它们,但它什么也没做。我没有编译错误/IntelliSense 警告。我做错了什么?

#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());
}

最佳答案

问题在于 dice 中的值类型为uint8_t ,其中cout::<<运算符解释为 unsigned char ,因此它将值打印为 ASCII 字符。但是,值介于 1 和 6 之间,并且 ASCII characters less than 32大多数是非打印字符,因此它们在输出中不可见。

说服cout::<<运算符将值打印为整数,请将代码更新为:

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
}

关于c++ - 来自类方法的 Cout 不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67980240/

相关文章:

c++ - 将变量的名称转换为 C++ 中的字符串?

python - 为创建类中定义的类创建类实例的引用

python - Django 表关系及其调用方式说明

c++ - 初始化 vector 对

java - 子字符串和 Vector.add 的问题

c++ - 从方法获取链表中的位置

c++ - 实现一个类似于 Qt 的高性能互斥锁

c++ - 如何进行腿部运动,OpenGL?

python - 如何在 Python 中创建新的未知或动态/扩展对象

java - 编写 Java 比较器