3

我有以下程序,我试图在其中了解\b转义序列的功能。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int disp(char *a) 
{
    return printf("%s", a); 
}

int main(void)
{
    char *s = "Hello\b\b";

    printf(" %d\n", disp(s));
    printf("%s %d\n", s, strlen(s));

    return 0;
}

输出:

$ ./a.out 
Hel 7
Hel 7
$ 

正如预期的那样Hello\b\b打印Hell,但strlen()返回 7 其中包括两个\b字符。

根据 C99 5.2.2\b定义如下:

\b (backspace) Moves the active position to the 
   previous position on the current line. If the 
   active position is at the initial position of 
   a line, the behavior of the display device is 
   unspecified.

如何\b在与字符串相关的函数中解释strlen()?和其他转义序列是否\b在编译时或运行时解析?

4

4 回答 4

9

\b是一个角色,就像您程序中的任何其他角色一样。只有当终端看到它时它才会变得特别。

ASCII 32 以下的字符被称为“控制字符”是有原因的:它们是向显示设备(即您的终端或控制台)发出的信号,表明它应该做一些特殊的事情,比如哔(\a)、向后移动光标(\b)或下一个制表位 ( \t)。

于 2011-12-29T20:57:43.583 回答
1

在运行时解决。字符串的长度包括\b长度,但“渲染引擎”控制台正在显示/执行退格。

于 2011-12-29T20:57:36.700 回答
1

strlen()将遍历作为参数给出的 char 指针,直到找到 0。

\b不是 0,这就是为什么你看到你看到的。

但是,与该角色相关的动作与您的输出设备相关联。

于 2011-12-29T20:57:50.823 回答
1

\b只影响输出。所有字符串函数仍将其视为一个字符。当您"Hello\b\b", 7显示时,会发生这种情况(使用 _ 表示光标位置):

H_
He_
Hel_
Hell_
Hello_
Hell_o  - cursor moves backwards
Hel_lo  - cursor moves backwards
Hel _o  - the space overwrites the "l"
Hel 7_  - the "7" overwrites the "o"
于 2011-12-29T20:58:08.777 回答