Linux sprintf 用 \n 写入字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8168572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 01:27:17  来源:igfitidea点击:

sprintf write to string with \n

clinuxprintf

提问by brunoais

I have this code:

我有这个代码:

str1= "a";
str2= "b";
sprintf(string, "0 %s %s\n", str1, str2);

string then contains:

字符串然后包含:

"0 a b"

instead of (what I want):

而不是(我想要的):

"0 a b
"

How can I solve that?

我该如何解决?

Note: I place the quoting of the var string inside " so that you could understand the situation.

Edit:

注意:我将 var 字符串的引用放在 " 中,以便您了解情况。

编辑:

Problem solvedI added 1 to the size and it worked. I don't completely understand why but it's solved

问题解决了我在大小上加了 1 并且它起作用了。我不完全明白为什么但它已经解决了

回答by Joshua Weinberg

It sounds like what you want is sprintf(string, "0 %s %s\n\n", str1, str2);

听起来你想要的是 sprintf(string, "0 %s %s\n\n", str1, str2);

In your example the string actually contains "0 a b\n" which means that anything printed after the \nwill appear on the next line. If you want a blank line below it, you need another line break.

在您的示例中,字符串实际上包含“0 ab\n”,这意味着在 之后打印的任何内容都\n将出现在下一行。如果你想在它下面有一个空行,你需要另一个换行符。

回答by Some programmer dude

If you are on a Windows computer you might need \r\ninstead of just the newline. The library should handle it though.

如果您使用的是 Windows 计算机,则可能需要\r\n而不仅仅是换行符。图书馆应该处理它。

回答by wannik

Allocate enough space for string

分配足够的空间 string

#include <stdio.h>
#include <stdarg.h>

main() {
    char string[7];
    char str1[] = "a";
    char str2[] = "b";
    sprintf(string, "0 %s %s\n", str1, str2);
    printf("%s", string);
}

回答by Sodved

Looks like its working for me. I put brackets []around the string to prove it.

看起来它对我有用。我[]在字符串周围加了括号来证明这一点。

Have a look here: http://ideone.com/3rbwF

看看这里:http: //ideone.com/3rbwF