C++ 如何在c++;?

C++ 如何在c++;?,c++,windows,colors,C++,Windows,Colors,所以我搜索了一下,找到了很多答案。我发现C++中没有标准的跨平台方式,操作系统管理颜色。例如,我发现在windows上,可以使用system(“color 1”)语句将颜色更改为文本(或前景),使用system(“color A”)将颜色更改为背景,或者使用system(“color 1A”)将两者都更改。但这将改变整个颜色,我想知道是否有一种方法可以改变它,即使是单个角色。就拿我刚才做的程序来说: #include<iostream> using namespace std;

所以我搜索了一下,找到了很多答案。我发现C++中没有标准的跨平台方式,操作系统管理颜色。例如,我发现在windows上,可以使用system(“color 1”)语句将颜色更改为文本(或前景),使用system(“color A”)将颜色更改为背景,或者使用system(“color 1A”)将两者都更改。但这将改变整个颜色,我想知道是否有一种方法可以改变它,即使是单个角色。就拿我刚才做的程序来说:

 #include<iostream>
using namespace std;  /* I prefer to use this because i think that's a huge time saver and it's also easier*/

void printRoad(int i)  /* That's my function, so by this function it prints a number of times choosed by the user 4 pieces of road*/
{
    int counter=1;
    while (counter <= i)
    {
        system("color 2");           /*Here is what i was talking about. I used the system("color 2") statement to change the text color
                                     from the default to green, but it changes the whole text.*/
        cout << "** | **" << endl;
        cout << "** | **" << endl;
        cout << "** | **" << endl;
        cout << "** | **" << endl;
        counter++;
    }
};
void main()  /*I don't need any specific return value from either the main() and the function so i thought it was a good idea to
             just use void.*/
{
    cout << "How many piece of roads do you want to build?" << endl;  /*Here it asks to the user what to do.*/
    int pieces = 0;
    cin >> pieces;
    printRoad(pieces);   //Here is the function call.


    system("pause");     /* Because i'm using windows and i'm using Visual Studio Express 2013 I used system("pause") to pause 
                         the program and let the user see the output.*/
}
#包括
使用命名空间std;/*我更喜欢用这个,因为我认为这是一个巨大的时间节省,而且更容易*/
void printRoad(int i)/*这是我的函数,因此通过该函数,它可以打印用户选择的4条道路*/
{
int计数器=1;

而(counter实际上,您可以使用它来代替调用system()

SetConsoleTextAttribute(GetStdHandle(标准输出句柄),颜色值)


据我所知,您只希望某个字符使用您选择的颜色。然后,在打印该字符后,您需要将其更改回默认值白色/灰色。

是的,这是我的意图。我非常喜欢这些类型的语句,因为它们与虚幻引擎4中使用的相同,但我不理解所有的。如果你能解释的话,这正是我想要的。非常感谢。实际上,这个方法非常简单。
SetConsoleTextAttribute()
需要两个参数。第一个是控制台中输出的句柄。你可以使用
GetStdHandle(STD\u output\u handle)获得这个参数
返回输出句柄。第二个参数是输出应采用的颜色值。例如,颜色类型为整数。如果您更改了一次颜色,并且希望下一个输出流采用默认颜色,则需要将其更改回去。我希望这能帮到您。因为没有默认颜色r您可以返回到,可能是更好的匹配,根据规范。它不会修改文字和背景颜色,超出编写的文字。是的,您是对的。但我认为您可以使用默认颜色,因为在控制台中它通常是灰色的。控制台颜色可根据用户进行配置。在我的系统中,管理员的颜色会有所不同ole没有默认的颜色。如果它变为我没有要求的颜色,我会非常生气。