【问题标题】:How to change Vector Objects into different colours?如何将矢量对象更改为不同的颜色?
【发布时间】:2020-05-31 18:05:44
【问题描述】:

我一直在尝试让我的代码将矢量对象更改为不同的颜色。我已经举例说明了我用于矢量和获取颜色的两种方法。有没有人知道如何做到这一点?

#include <iostream>
#include <vector>
#include <windows.h>

std::vector<std::string> playerInventory;

int main() {

    HANDLE color = GetStdHandle(STD_OUTPUT_HANDLE); //just once
    SetConsoleTextAttribute(color, 10);
    std::cout << "This";
    SetConsoleTextAttribute(color, 11);
    std::cout << " is";
    SetConsoleTextAttribute(color, 12);
    std::cout << " a";
    SetConsoleTextAttribute(color, 13);
    std::cout << " colour";
    SetConsoleTextAttribute(color, 14);
    std::cout << " combination" << std::endl;

    playerInventory.push_back("1");
    playerInventory.push_back("2");
    playerInventory.push_back("3");
    playerInventory.push_back("4");

    for (int x = 0; x != playerInventory.size(); ++x)
    {
        std::cout << playerInventory[x] << std::endl;
    }
}

【问题讨论】:

    标签: c++ vector colors


    【解决方案1】:

    您似乎已经知道如何更改颜色,因此您只需更改循环内的颜色,为向量的每个元素。示例:

    for ( int x = 0; x != playerInventory.size(); ++x ) {
        SetConsoleTextAttribute( color, 10 + x );
        std::cout << playerInventory[x] << std::endl;
    }
    

    但请记住,SetConsoleTextAttribute's wAttribute parameter 中的有效值只有这么多

    【讨论】:

    • 谢谢!这真的很有用。如果我想说有一个双字矢量对象,例如:“playerInventory.push_back("Hello There");”,我将如何让第一个单词变成一种颜色,第二个单词变成另一种颜色?
    • @Oxic,您需要逐字拆分字符串,并做同样的事情。 SO上有很多关于拆分字符串的例子,你可以看看。
    猜你喜欢
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多