在多行上定义一个字符串

请采取以下措施:

char buffer[512]; memset(buffer, 0, sizeof(buffer)); sprintf(&buffer[0],"This Is The Longest String In the World that in text goes on and.."); printf("Buffer:%s\r\n",buffer); 

我希望能够在多行上创建此字符串,以便于故障排除和编辑。 但是,当我使用\命令时,我的输出被看似是标签的东西分开了?

例:

 sprintf(&buffer[0],"This Is The\ Longest String In the World\ that in text goes on and.."); 

产生一个输出:

 Buffer:This Is The Longest String In the World that in text goes on and.. 

有任何想法吗? 这只是一种尝试在多行代码中分解字符串的错误方法吗?

换行符继续考虑代码中的任何空格。

您可以利用字符串文字串联来获得更好的可读性:

 sprintf(buffer, "This Is The " "Longest String In the World " "that in text goes on and.."); 

使用\你需要在第0列开始继续你的字符串:

 sprintf(buffer, "This Is The \ Longest String In the World \ that in text goes on and.."); 

虽然这可能看起来很迂腐,但在现实世界中,我已经被咬了足够多次,以便在其他两个答案中遇到以下问题。

  • 两个发布的答案忽略了在连接单独的字符串文字的单词之间给出空格(显然,在第一次测试之后)。

  • 如果您的字符串非常长,请使用snprintf() – 它稍微笨拙,但它告诉任何人检查您的代码,您知道代码维护中的常见危险。

  • 如果您的字符串恰好包含% ,您将收到编译器警告(好)或随机分段错误(错误)。 所以使用"%s"或者在这种情况下,只需使用strcpy(). (两个月后,同事可以轻松地将99.9%添加到邮件中。)

  • 我经常看到的memset(),的使用只是货物编程。 是的,在特殊情况下需要它,但是一直使用它会发送错误信息。

  • 最后,为什么只有buffer会有人使用&buffer[0]

总而言之,您的代码应该是:

 char buffer[512]; snprintf(buffer, sizeof buffer, "%s", "This is The Longest String " "In the World that in text " "goes on and on and on and on ...."); printf("Buffer:%s\r\n", buffer); 

这也可以正常工作:

 char buffer[512]; sprintf(&buffer[0], "This is the longest string" "in the world that in text" "goes on and on and on and on ...."); printf("%s\n", buffer);