如何在每一行数组C++中进行颜色更改

How to make color changes in every line array C++

本文关键字:C++ 颜色 数组 一行      更新时间:2023-10-16

我有一个问题要问这个网站上的每个人。我想在每一行中更改数组语句的颜色。我的意思是,数组语句的每一行都有不同的颜色。这是我的程序

#include<conio.h>
#include<windows.h>
#include<iostream>
using namespace std;
int main()
{
    system("color 0B");
    ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
    cout<<"n Printing array index in char program";
    char data[27]={' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    int x;
    for(x=0;x<28;x++)
    {
        cout<<"nn Input array index : ";
        cin>>x;
        cout<<"Character you are looking for is "<<data[x];
    }
    getch();
}

我想在cout<<"nn Input array index : ";语句和cout<<"Character you are looking for is "<<data[x];语句中更改颜色。请帮帮我:)

您可以使用像SetConsoleTextAttribute:这样的Windows控制台功能

SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN);
std::cout << "This text should be green" << std::endl;

免责声明:我真的不知道(也无法测试)它是否能与C++标准输出流一起工作,或者你是否必须使用WriteConsole

如果使用conio,则可以使用textcolor (int)进行着色。

#include <windows.h>
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
    ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
    cout<<"n Printing array index in char program";
    char data[27]={' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    int x;
    for(x=0;x<27;x++)
    {
        textcolor(x+1);
        cout<<"nn Input array index : ";
        cin>>x;
        cout<<"Character you are looking for is "<<data[x];
    }
    getch();
}

如果你没有使用conio,那么试试这个

#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
    HANDLE  hConsole;
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
    cout<<"n Printing array index in char program";
    char data[27]={' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    int x;
    for(x=0;x<27;x++)
    {
        SetConsoleTextAttribute(hConsole, x+1);
        cout<<"nn Input array index : ";
        cin>>x;
        cout<<"Character you are looking for is "<<data[x];
    }
}

小建议不要使用conioconio.h确实不是标准的C头。