gpt4 book ai didi

c - 为什么 printf 语句不继续下一行?

转载 作者:行者123 更新时间:2023-12-02 15:45:43 25 4
gpt4 key购买 nike

考虑这个程序:

#include <stdio.h>

int main()
{
int a;
a = 16;

printf("This is the first line
this is the second line
");
}

为什么这个程序会抛出错误?为什么它不能编译成功并显示输出为:


This is the first line
this is the second line
|

符号'|'这里表示闪烁的光标,表示光标移动到下一行,表示在“第二行”之后出现了STDOUT中的'\n'字符。

                                              .

最佳答案

在 ISO C 中,一个 string literal必须在单行代码中,除非紧接在行尾之前有一个 \ 字符,如下所示:

#include <stdio.h>

int main()
{
int a;
a = 16;

printf("This is the first line\
this is the second line\
");
}

但是,这将打印以下内容:

This is the first line    this is the second line 

如您所见,缩进也被打印出来了。这不是您想要的。

你可以做的是在不同的行上定义几个彼此相邻的字符串文字,添加一个 \n escape sequence必要时。

#include <stdio.h>

int main()
{
int a;
a = 16;

printf(
"This is the first line\n"
"this is the second line\n"
);
}

相邻的字符串文字将自动合并到 phase 6 of the translation process 中.

这个程序有期望的输出:

This is the first line
this is the second line

关于c - 为什么 printf 语句不继续下一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74319816/

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