[在搜索K&R C练习7-2的语句的含义时,我找到了关于https://clc-wiki.net/wiki/K%26R2_solutions:Chapter_7:Exercise_2上K&R C练习7.2的答案
练习要求
编写一个程序,该程序将以明智的方式打印任意输入。至少应根据本地习惯以八进制或十六进制打印非图形字符,并打断长文本行。
此外,我也无法理解练习句子的含义,特别是“至少应根据当地习惯以八进制或十六进制打印非图形字符的部分。”
此练习7-2要求什么?请解释锻炼声明的含义。
下面的代码在代码末尾使用格式说明符“%02x”和“%3o”来打印不可打印的字符,但是此格式说明符对Non-Printables的作用是什么?
else
{
if(textrun > 0 || binaryrun + width >= split)
{
printf("\nBinary stream: ");
textrun = 0;
binaryrun = 15;
}
printf(format, ch);
binaryrun += width;
}
其余代码将长行分成较小的行,并照原样打印所有可打印字符。
完整程序如下:
#include <stdio.h>
#define OCTAL 8
#define HEXADECIMAL 16
void ProcessArgs(int argc, char *argv[], int *output)
{
int i = 0;
while(argc > 1)
{
--argc;
if(argv[argc][0] == '-')
{
i = 1;
while(argv[argc][i] != '\0')
{
if(argv[argc][i] == 'o')
{
*output = OCTAL;
}
else if(argv[argc][i] == 'x')
{
*output = HEXADECIMAL;
}
else
{
/* Quietly ignore unknown switches, because we don't want to
* interfere with the program's output. Later on in the
* chapter, the delights of fprintf(stderr, "yadayadayada\n")
* are revealed, just too late for this exercise.
*/
}
++i;
}
}
}
}
int can_print(int ch)
{
char *printable = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 !\"#%&'()*+,-./:;<=>?[\\]^_{|}~\t\f\v\r\n";
char *s;
int found = 0;
for(s = printable; !found && *s; s++)
{
if(*s == ch)
{
found = 1;
}
}
return found;
}
int main(int argc, char *argv[])
{
int split = 80;
int output = HEXADECIMAL;
int ch;
int textrun = 0;
int binaryrun = 0;
char *format;
int width = 0;
ProcessArgs(argc, argv, &output);
if(output == HEXADECIMAL)
{
format = "%02X ";
width = 4;
}
else
{
format = "%3o ";
width = 4;
}
while((ch = getchar()) != EOF)
{
if(can_print(ch))
{
if(binaryrun > 0)
{
putchar('\n');
binaryrun = 0;
textrun = 0;
}
putchar(ch);
++textrun;
if(ch == '\n')
{
textrun = 0;
}
if(textrun == split)
{
putchar('\n');
textrun = 0;
}
}
else
{
if(textrun > 0 || binaryrun + width >= split)
{
printf("\nBinary stream: ");
textrun = 0;
binaryrun = 15;
}
printf(format, ch);
binaryrun += width;
}
}
putchar('\n');
return 0;
}
您已经自己发现“%02x”和“%03o”是什么意思。很好!
所以您的问题归结为“什么是不可打印的字符?”和“如何以上述格式打印?”
[不可打印的字符由函数printable
中的字符串can_print()
定义(在所示的源中)。故意将不在此字符串中的所有字符定义为不可打印。 我们可以对选择进行推理,但这不在本文范围内。另一个注意事项:“”和“ \ t \ f \ v \ r \ n”在这组可打印字符中,其值以ASCII为<= 0x20。
顺便说一句,标准库具有用于检查可打印性的isprint()
。
您似乎知道每个字符都被编码为一个分配值。您可以根据需要将其解释为任何字符,字符,数字,指令,颜色,位模式。实际上,所有数字计算机都只是在处理位模式,这取决于它们的含义。
因此,不可打印的字符可以解释为int
数字,这就是上述格式的printf()
会发生的情况。假设读取的字符为'\ b',称为退格键。 ((注意:它不在printable
中。)]在ASCII中,此字符编码为0x08。因此输出分别为“ 08”和“ 010”。
您可能希望以all字符不可打印的方式更改程序。然后,您将看到所有字符输出为十六进制或八进制。