15

请采取以下措施:

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..

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

4

3 回答 3

23

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

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

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..");
于 2012-10-02T17:02:48.017 回答
8

尽管这可能看起来很迂腐,但在现实世界中,我已经被咬了足够多的时间,以至于与其他两个发布的答案存在以下问题。

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

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

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

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

  • 最后,为什么有人会使用&buffer[0]when just buffer would do?

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

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);
于 2012-10-02T17:49:46.793 回答
4

这也可以正常工作:

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);
于 2012-10-02T17:04:19.477 回答