我如何在c++中改变颜色

How can i change colors in c++?

本文关键字:改变 变颜色 c++      更新时间:2023-10-16

所以我搜索了它,我找到了很多答案。我发现在c++中没有标准的跨平台方法来做到这一点,并且操作系统管理颜色。例如,我发现在windows上,您可以使用system("color 1")语句来更改文本(或前景)的颜色,并使用system("color A")来更改背景的颜色,或者两个系统("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.*/
}

那么,如果,例如,我想改变每条道路的颜色呢?就像第一个伯爵<<"** | **"<<p>我也看到很多人抱怨system(")语句的使用。我理解这一点,因为这样你的程序就失去了跨平台的能力。但如果游戏依赖于我们所使用的系统,我们该如何保持跨平台功能?谢谢你的回答。

实际上你可以用它来代替调用system():

SetConsoleTextAttribute (GetStdHandle (STD_OUTPUT_HANDLE) ValueOfColour);

据我所知,你的问题是,你只想要一个特定的字符在你选择的颜色。然后,您需要将其更改回默认值白色/灰色后,这个字符被打印。