gpt4 book ai didi

c++ - 了解此打印结果

转载 作者:行者123 更新时间:2023-12-02 10:04:24 26 4
gpt4 key购买 nike

我尝试在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中:

  • 10代表'\n'
  • 13代表'\r'

  • \ n(换行符):

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

    \ r(回车):

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

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

    情况1

    打印 text =“12 \ rn3 \ r34”
  • 打印1 {1}
  • 打印2 {12}
  • \r光标返回(到1){12}
  • 打印n(覆盖1){n2}
  • 打印3(覆盖2){n3}
  • \r光标返回(至n){n3}
  • 打印4(覆盖n){43}

  • 因此,输出为 43

    情况二

    打印 text =“12 \ rn3 \ r345”

    与前面的步骤1-7 {43}相同
  • 打印5(覆盖3){45}

  • 因此,输出为 45

    情况3

    打印 text =“12 \ nn3 \ n45”
  • 打印1
  • 打印2
  • \n光标转到下一行
  • 打印n
  • 打印3
  • \n光标转到下一行
  • 打印4
  • 打印5

  • 因此,输出为

    12

    n3

    45

    关于c++ - 了解此打印结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60984128/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com