【发布时间】:2022-01-12 19:09:37
【问题描述】:
我正在尝试使用 printf 为我的字符串添加颜色,例如
printf("\x1B[92m%d\033[0m", value1);
这对我来说用整数没问题,但是当我尝试做类似的事情时
printf("\x1B[92m%s\033[0m", wantedString);
我得到一些随机的东西,例如,(°√,有什么帮助吗?
这是整个函数
void searchFileFor(path const& files, string wantedString) {
ifstream inFile;
string currentString;
int lineNumber = 0;
bool foundNothing = true;
for (auto file : recursive_directory_iterator(files)) {
lineNumber = 0; // Reset after each new file
inFile.open(file);
while (inFile >> currentString) {
lineNumber++;
if (currentString.find(wantedString) != string::npos) {
cout << file << " " << wantedString << " " << lineNumber << '\n';
foundNothing = false;
}
//cout << file << " " << currentString << endl;
}
inFile.close();
}
if (foundNothing == true) {
cout << "We were not able to find: " << wantedString << "";
printf("\x1B[92m%s\033[0m", wantedString);
}
//cout << "Wanted String: " << wantedString;
}
【问题讨论】:
-
wantedString中有什么内容? -
您可能需要
wantedString.c_str()。printf()没有std::string的概念。 -
不要使用 printf:
std::cout << "\x1B[92m" << wantedString << "\033[0m" -
启用compiler warnings 应该会提醒您注意该问题。
-
您为什么同时使用
\x1B和\033?你喜欢折磨维护者吗?