了解此printf的结果



我试图在char数组中使用"回车"ASCII值,然后使用printf("%s"(打印字符串,但我得到了奇怪的结果。

这是我的代码:

#include <iostream>
int main(){
char text[10];
text[0] = '1';
text[1] = '2';
text[2] = 13;
text[3] = 'n';
text[4] = '3';
text[5] = 13 ;
text[6] = '4';
printf("%s", text);
}

输出为:43

但是当我在数组中添加一个字符时,如下所示:

#include <iostream>
int main(){
char text[10];
text[0] = '1';
text[1] = '2';
text[2] = 13;
text[3] = 'n';
text[4] = '3';
text[5] = 13;
text[6] = '4';
text[7] = '5';
printf("%s", text);
}

输出为45

然后我使用字符10而不是像这样的13

#include <iostream>
int main(){
char text[10];
text[0] = '1';
text[1] = '2';
text[2] = 10 ;
text[3] = 'n';
text[4] = '3';
text[5] = 10 ;
text[6] = '4';
text[7] = '5';
printf("%s", text);
}

输出变为:

12
n3
45

有人能向我解释一下第一次输出和第二次输出之间差异的原因吗?

字符10和字符13在函数printf("%s")处理它们的方式上有什么不同?

在ASCII中:

  1. 10代表'n'

  2. 13代表'r'

\n(换行(

将活动位置移动到下一行的初始位置。

\r(回车(:

将活动位置移动到当前行的初始位置。

继续操作之前,请确保字符串以null结尾。添加以标记字符串的末尾并避免未定义的行为

案例1

打印text="12\rn3\r34">

  1. 打印1{1}

  2. 打印2{12}

  3. r光标返回(到1({12}

  4. 打印n(覆盖1({n2}

  5. 打印3(覆盖2({n3}

  6. r光标返回(到n({n3}

  7. 打印4(覆盖n({43}

因此,输出为43

案例2

打印text="12\rn3\r345">

与前面的步骤1-7相同{43}

  1. 打印5(覆盖3({45}

因此,输出为45

案例3

打印text="12\nn3\n45">

  1. 打印1个

  2. 打印2

  3. n光标转到下一行

  4. 打印n

  5. 打印3

  6. n光标转到下一行

  7. 打印4

  8. 打印5

因此,输出为

12

n3

45

最新更新