1. 主页
  2. 文档
  3. C语言教程
  4. C语言数组和字符串
  5. 如何在多行 C/C++ 中编写长字符串

如何在多行 C/C++ 中编写长字符串

想象一个我们想在 C 或 C++ 中使用或打印一个长长的字符串的情况,如何做到这一点?

在 C/C++ 中,我们可以在中间的任意点使用中间的两个双引号来分隔字符串。下面是一个简单的例子来证明这一点。

#include<stdio.h>
int main()
{
// 我们可以在字符串的任意位置放置两个双引号
char *str1 = "52""cxydh"; 

// 我们可以在两个双引号之间放置空格换行符
char *str2 = "52" "Cxydh";
char *str3 = "52" 
"Cxydh";

puts(str1);
puts(str2);
puts(str3);

puts("52" // Breaking string in multiple lines
"cxydh");
return 0;
}
输出:
52cxydh
52Cxydh
52Cxydh
52cxydh

下面是几个使用两个双引号分隔长字符串以提高可读性的示例。

#include<stdio.h>
int main()
{
char *str = "These are reserved words in C language are int, float, "
"if, else, for, while etc. An Identifier is a sequence of"
"letters and digits, but must start with a letter. "
"Underscore ( _ ) is treated as a letter. Identifiers are "
"case sensitive. Identifiers are used to name variables,"
"functions etc.";
puts(str);
return 0; 
} 

输出:

These are reserved words in C language are int, float, if, else, for, while etc. An Identifier is a sequence ofletters and digits, but must start with a letter. Underscore ( _ ) is treated as a letter. Identifiers are case sensitive. Identifiers are used to name variables,functions etc.
#include<stdio.h>
int main()
{
char *str = "An Identifier is a sequence of"
"letters and digits, but must start with a letter. "
"Underscore ( _ ) is treated as a letter. Identifiers are "
"case sensitive. Identifiers are used to name variables,"
"functions etc.";
printf ("These are reserved words in C language are int, float, "
"if, else, for, while etc. %s ", str);
return 0; 
}

输出:

These are reserved words in C language are int, float, if, else, for, while etc. An Identifier is a sequence ofletters and digits, but must start with a letter. Underscore ( _ ) is treated as a letter. Identifiers are case sensitive. Identifiers are used to name variables,functions etc.

 

这篇文章对您有用吗?