C++ SetConsoleTextAttribute 更改字符串中的字符

标签 c++ string winapi

我有一个包含一些字符的 C++ 字符串。如果遇到某些字符,如何更改字符颜色?下面是示例代码:

#include <iostream>
#include "windows.h"
using namespace std;
int main()
{
    HANDLE h;
    h = GetStdHandle(STD_OUTPUT_HANDLE);
    string str = "my name is meow.";
    for(int i=0; i<str.length(); i++)
    {
        if(str[i] == 'm')
        {
            //change the char 'm' to red color..
        }

        cout<<str[i];
    }
    return 0;
}

最佳答案

 if(str[i] == 'm')
  {
     SetConsoleTextAttribute(h, FOREGROUND_RED);
     cout<<str[i]; 
  }
 else
  {
     SetConsoleTextAttribute(h, 15);
     cout<<str[i];
  }

也许这就是你想做的?

关于C++ SetConsoleTextAttribute 更改字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17571900/

相关文章:

C++自定义按钮图标

c++ - 了解 C++ 中的自删除程序

c++ - 在 C++ 中使用 ifstream

c++ - 这是逗号运算符的可接受用法吗?

c# - 为什么使用此代码在运行时得到 "Invalid args"?

c++ - 在 Windows 上处理用户 session 的关闭状态?

c++ - 在一行中读取 SMTP 邮件

c++ - Qt 在 Mac OSX 10.9 上的部署

python - 为什么python2中 '1' == u'1'的结果是True?

c++ - C++1 1's std::string' 的底层表示是否保证有终止空字符?