所以我搜索了它,我找到了很多答案。我发现在c ++中没有标准的跨平台方法可以做到这一点并且操作系统管理颜色。例如,我发现在Windows上您可以使用系统(“颜色1”)语句将颜色更改为文本(或前景)和系统(“颜色A”)以将颜色更改为背景,或两个系统(“颜色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.*/
}
那么,例如,如果我想改变每一种道路颜色呢?像第一个cout&lt;&lt;“** | **”&lt;
我还读过很多人抱怨使用系统(“”)语句。我理解它是因为这样做会导致您的程序失去跨平台能力。但如果事情依赖于我们所处的系统,那么我们应该如何通过保持跨平台能力来实现呢?谢谢你的回答。
答案 0 :(得分:0)
实际上你可以使用它而不是调用 system() :
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),ValueOfColour);
据我了解你的问题,你只希望某个角色处于你选择的颜色。然后,您需要在打印此字符后将其更改回默认值white / gray。