2013-08-28 113 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************************/ 
相关问题