2011-12-29 340 views
3

我有以下程序,我試圖瞭解\b轉義序列的功能。 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打印Hellstrlen()返回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和其他轉義序列嗎?

回答

9

\b是一個字符,就像程序中的任何其他字符一樣。只有終端看到它纔會變得特別。

下面ASCII 32字符被稱爲「控制字符」的一個原因:他們是一個信號,顯示設備,即你的終端或控制檯,它應該做一些特別的東西,比如音(\a),移動光標向後(\b)或下一個製表符(\t)。

+4

實際上,它們被稱爲「控制字符」。 「轉義」是指用於改變後續字符含義的特定控制字符。 – 2011-12-29 21:12:36

+0

@HotLicks:好的,謝謝。 – thiton 2011-12-29 21:13:53

+0

(好帖子,否則 - 我給它+1) – 2011-12-29 22:09:48

1

運行時解決。字符串的長度包括長度爲\b,但控制檯「渲染引擎」正在顯示/執行退格。

1

strlen()會爲什麼你看到你所看到的,直到它找到0

\b不爲0作爲參數給出的字符指針走了過來,這是。

但是,鏈接到此字符的操作鏈接到您的輸出設備。

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"