sam*_*moz 6 c++ formatting printf cout
我正在编写一个程序,使用打印输入的十六进制转储.但是,当传入换行符,制表符等并破坏输出格式时,我遇到了问题.
我怎样才能使用printf(或我猜想)打印'\n'而不是打印实际的换行符?我只需要为此进行一些手动解析吗?
编辑:我动态地接收我的数据,它不仅仅是我所关注的,而是所有符号.例如,这是我的printf语句:
printf("%c", theChar);
Run Code Online (Sandbox Code Playgroud)
当换行符作为theChar传入时,如何进行此打印\n但是当theChar是有效的可打印字符时仍然使其打印正常文本?
Jar*_*aus 22
printchar()下面的函数会将某些字符打印为"特殊",并打印超出范围的字符的八进制代码(a la Emacs),否则打印普通字符.我也冒昧地'\n'打印出一个真实的产品'\n',使你的输出更具可读性.还要注意我int在循环中使用一个main只是为了能够迭代整个范围unsigned char.在您的使用中,您可能只是unsigned char从数据集中读取的内容.
#include <stdio.h>
static void printchar(unsigned char theChar) {
switch (theChar) {
case '\n':
printf("\\n\n");
break;
case '\r':
printf("\\r");
break;
case '\t':
printf("\\t");
break;
default:
if ((theChar < 0x20) || (theChar > 0x7f)) {
printf("\\%03o", (unsigned char)theChar);
} else {
printf("%c", theChar);
}
break;
}
}
int main(int argc, char** argv) {
int theChar;
(void)argc;
(void)argv;
for (theChar = 0x00; theChar <= 0xff; theChar++) {
printchar((unsigned char)theChar);
}
printf("\n");
}
Run Code Online (Sandbox Code Playgroud)
如果你想确保你没有打印任何非打印字符,那么你可以使用的功能ctype.h类似isprint:
if( isprint( theChar ) )
printf( "%c", theChar )
else
switch( theChar )
{
case '\n':
printf( "\\n" );
break;
... repeat for other interesting control characters ...
default:
printf( "\\0%hho", theChar ); // print octal representation of character.
break;
}
Run Code Online (Sandbox Code Playgroud)