我想让我的控制台更加丰富多彩.如何在用户输入时使用户输入(通过getline获得)

I want to make my console more colorful. How can I make the user input (obtained through getline) colorful while they type?

本文关键字:用户 输入 通过 获得 getline 我的 控制台 丰富多彩      更新时间:2023-10-16

我只是想知道在用户将其键入控制台时是否可以为文本上色。

我正在为cout'ED文本使用颜色库,但是我想知道在用户输入他/她的字符串时是否可以上色?

您可以使用Windows Console API进行此操作:

HANDLE console_output = ::GetStdHandle(STD_OUTPUT_HANDLE);
::SetConsoleTextAttribute(console_output, FOREGROUND_GREEN);
std::string buffer;
std::getline(std::cin, buffer);
std::cout << buffer << std::endl;
::CloseHandle(console_output);

输入文本的颜色为绿色。另外,不要忘记包括Windows.h

在Linux/MacOS上只做以下操作:

#include <iostream>
int main()
{
  std::string foo;
  std::cout << "Type your text here : x1B[31m";
  std::cin >> foo;
  std::cout << "x1B[0m" << std::endl;
  std::cout << "Your input : " << foo << std::endl;
  return (0);
}

litte解释:

键入以下特定字符串之一:

"x1B[31m" (red)
"x1B[32m" (green)
"x1B[33m" (yellow)
"x1B[34m" (blue)
"x1B[35m" (magenta)
"x1B[36m" (cyan)
"x1B[0m" (reset)

它将使用TermCap(代表终端功能),并更改后所有输出的颜色。使用这些Termcap后,不要忘记重置,否则您的终端将粘在所选的颜色上,直到您将其重置为止。

ps:不知道它是否适用于Windows。