Windows 命令提示符中的彩色文本在一行中
colored text in windows command prompt in one line
我想在Windows命令提示符下更改特定的单词颜色,它的工作原理很好:
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
string setcolor(unsigned short color){
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hcon, color);
return "";
}
int main(int argc, char** argv)
{
setcolor(13);
cout << "Hello ";
setcolor(11);
cout << "World!" << endl;
setcolor(7);
system("PAUSE");
return 0;
}
但我希望我的函数像这样工作
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
string setcolor(unsigned short color){
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hcon, color);
return "";
}
int main(int argc, char** argv)
{
cout << setcolor(13) << "Hello " << setcolor(50) << "World!" << setcolor(7) << endl;
system("PAUSE");
return 0;
}
当我运行它时,只有setcolor(13)工作,然后颜色永远不会改变直到最后,我应该怎么做才能解决这个问题
我的评论可能是错误的,使用 I/O 操纵器(如 std::setw
和家人)可能是可能的:
struct setcolor
{
int color;
setcolor(int c) : color(c) {}
std::ostream& operator()(std::ostream& os)
{
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hcon, color);
return os;
}
};
像以前一样使用它:
std::cout << "Hello " << setcolor(50) << "worldn";
注意:我不知道这是否有效,因为我还没有测试过它。
您现在使用当前代码(如问题所示)遇到的问题是setcolor
是一个返回字符串的普通函数,您只需调用这些函数并打印它们的返回值(空字符串)。
您需要将输出放入一个单独的函数中:
void WriteInColor(unsigned short color, string outputString)
{
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hcon, color);
cout << outputString;
}
然后,您可以致电
int main(int argc, char** argv)
{
WriteInColor(13, "Hello");
WriteInColor(50, "World");
WriteInColor(7, "rn");
}
仍然不是单衬垫,但比您的第一个选择更干净:)
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何使代码打印文本文件中的第一行?
- 如何在C++中以这种方式返回一行文本?
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 需要从存档中读取一行文本.txt直到找到"hhh",然后转到下一行
- 如何在c ++中以一行(水平)打印两个文件的数据?如给定的.这两种形式来自两个不同的文本文件
- 到达分隔符时跳到文本文件的下一行
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 从文本文件中随机选取一行
- 以 LPCTSTR 开头编写另一行文本的最佳方法是什么?
- C++ ->尝试逐字阅读一行文本。如何使指针等效于用于存储输入的当前二维数组
- 如何让控制台在输入一行文本时输出某些内容
- 如何使用预处理器从源文件中获取一行文本
- 用c++将文件中的一行文本复制到字符串中
- 如何在控制台项目中重写一行文本?c++
- 如何从文件中读取一行文本而不跳过空行?
- 使用正则表达式从C++中的一行文本中提取数据
- 如何在不知道一行文本有多少元素的情况下读取每个元素?(c++)
- 在C++中读取一些整数,然后读取一行文本