2013-08-28 116 views
1

它始終顯示「hello world」。爲什麼?printf不打印完整字符串

#include <stdio.h> 

int main(void) 
{ 
    printf("..... world\rhello\n"); 
    return 0; 
} 
+5

你*知道什麼字符''\ r''(也被稱爲回車符)呢? –

+0

http://en.wikipedia.org/wiki/Carriage_return – Bart

+1

@ user2693578你有沒有忘記重新編譯你的代碼? – Nbr44

回答

9

這是因爲\rcarriage return(CR)。它將插入符號返回到行首。之後,您在那裏寫入hello,有效覆蓋點。在另一方面

\n(換行,LF)用於移動插入符只是一個線向下,這就是爲什麼電傳打字機具有序列CR-LF,或回車後跟行進料以定位插入符在下一行的開始。 Unix消除了這一點,LF現在自己做。不過,CR仍然存在於舊的語義中。

+0

下一個問題是:這是由任何標準保證,還是UB? – Medinoc

+1

「\ r」和「\ n」都沒有標準化以映射到特定字符(例如,U + 000A和U + 000D是慣例,但不是必需的)。寫入時,\ n「透明地轉換爲系統的換行順序,而在分別讀取文本模式時完成反轉。 – Joey

2

因爲孤獨\rcarriage return)字符導致您的終端返回到行的開頭,而不更改行。因此,\r左側的字符被"hello"覆蓋。

4

使用\r要返回到當前行的開頭and're覆蓋點「.....」:

printf("..... world\rhello\n"); 
     ^^^^^  vvvvv 
     hello <----- hello 

工作原理:

..... world 
     ^

然後返回到開始當前行:

..... world 
^ 

然後pr在\r之後插入一個單詞。其結果是:

hello world 
     ^
0

檢查一遍,它會發出讓像

..... world 
hello 

什麼等過你寫裏面的printf(),它會返回作爲輸出

0
#include<stdio.h> 
#include<conio.h> 
int main(void) 

{ 
    // You will hear Audible tone 3 times. 
    printf("The Audible Bell --->   \a\a\a\n"); 
    // \b (backspace) Moves the active position to the 
    // previous position on the current line. 
    printf("The Backspace --->    ___ \b\b\b\b\b\b\b\b\b\bTesting\n"); 
    //\n (new line) Moves the active position to the initial 
    // position of the next line. 
    printf("The newline ---> \n\n"); 
    //\r (carriage return) Moves the active position to the 
    // initial position of the current line. 
    printf("The carriage return --->  \rTesting\rThis program is for testing\n"); 
    // Moves the current position to a tab space position 
    printf("The horizontal tab --->   \tTesting\t\n"); 

    getch(); 
    return 0; 
} 

/***************************OUTPUT************************ 
The Audible Bell ---> 
The Backspace --->      Testing__ 
The newline ---> 

This program is for testing 
The horizontal tab --->       Testing 
***************************OUTPUT************************/ 
相關問題