带有特殊字符的字符串的控制台输出
Console output of strings with special characters
是否有一种或多或少的标准方法来输出包含特殊字符的字符串,例如 ASCII 控制代码,以使输出是有效的 C/C++ 文字字符串,带有转义序列?
预期输出示例:Thisnisna\testnnShe said, "How are you?"n
如果不小心,输出将是
This
is
atest
She said, "How are you?"
不是想要的。
打印转义字符串显然很棘手。
问题包括
- 控制字符和空字符。 转
- 义转义字符。
- 负面
char
. 十六进制转义序列没有指定的长度限制。 八进制限制为 3 位数字。
void EscapePrint(char ch) { // 1st handle all simple-escape-sequence C11 6.4.4.4 // The important one to detect is the escape character `` // Delete or adjust these 2 arrays per code's goals static const char *escapev = "abtnvfr"'?\"; static const char *escapec = "abtnvfr"'?\"; char *p = strchr(escapev, (unsigned char) ch); if (p && *p) { printf("\%c", escapec[p - escapev]); } // if printable, just print it. else if (isprint((unsigned char) ch)) { fputc(ch, stdout); } // else use octal escape else { // Use octal as hex is problematic reading back printf("\%03hho", ch); } }
迂腐:八进制转义序列在char
范围超过 9 位的稀有机器上是一个问题。 这可以通过字符串级别的十六进制转义序列来处理,而不是在char
基础上char
处理,因为十六进制转义序列需要限制。 例:
input 2 `char`: 1 A
// v----- intervening space
output text including ": "\x1" "A"
根据您可能尝试实现的目标,我可以建议以下解决方案:只需将任何不可打印的字符替换为"\xnn"(nn 是字符的 ascii 代码。这将归结为
void myprint (char *s) {
while (*s) {
printf(isalnum((unsigned char) *s) ? "%c" : "\%03hho", *s);
s++;
}
}
这当然不会使用像n
(但x0a
)这样的特殊缩写,但这应该不是问题。
如果它对某人有帮助,我很快就把它放在一起:
void printfe(char* string)
{
for (char c= *string; c; c= *(++string))
{
switch (c)
{
case 'a': printf("\a"); break;
case 'b': printf("\b"); break;
case 'f': printf("\f"); break;
case 'n': printf("\n"); break;
case 'r': printf("\r"); break;
case 't': printf("\t"); break;
case 'v': printf("\v"); break;
case '': printf("\\"); break;
case ''': printf("'"); break;
case '"': printf("\""); break;
case '?': printf("\?"); break;
default: (c < ' ' || c > '~') ? printf("\%03o", c) : putchar(c); break;
}
}
}
(注意c < ' ' || c > '~'
的潜在不可移植性,我想避免任何库引用)。
相关文章:
- C++:将控制台输出存储在宏中更好吗
- 在Qt Creator中,如何在连接到正在运行的进程后查看控制台输出
- 控制台输出在 Qt5 中未正确显示
- 有人可以向我解释为什么控制台输出 0 吗?
- 使用 std::string_view 的子字符串控制台输出
- C++ 如何暂停控制台输出,以便用户可以在继续之前阅读信息
- 我如何阅读简单的控制台输出
- 是否可以在 RTL(从右到左)中制作控制台输出?
- 如何让控制台输出覆盖控制台而不是纯文本输出?
- 乱码控制台输出管道 stderr 到更多
- 将控制台输出写入.txt并在控制台上显示
- 当被一个输入分开时,有两个控制台输出同时显示
- VSCode C++调试捕获控制台输出
- 如何将控制台输出中的所有内容复制到文本文件?
- C++ 使用简单的代码同时写入文件和控制台输出
- 使控制台输出是否"verbose"的最快方法
- 将 ffmpeg 控制台输出重定向到C++中的字符串或文件
- C++ 控制台输出到 cmd 在重复十次后出错
- 从控制台输出读取 C++
- 如何将控制台输出的文本颜色更改为红色,但如果从Powershell或CMD运行,背景将保持相同的颜色