如何在不打印尾随换行符的情况下使用printf打印字符串 [英] How to print a string using printf without it printing the trailing newline
问题描述
我正在尝试使用printf()
打印一些字符串,但是它们以 null终止,并带有尾随换行符,并且与格式混乱:
I'm trying to print some strings using printf()
but they are null terminated having trailing newline and that messes with the formating:
printf("The string \"%s\" was written onto the file \"%s\"", str, fname);
说字符串包含"The Racing car."
,文件名是"RandomText1.txt"
打印:
Say the string contains "The Racing car."
and the file name is "RandomText1.txt"
This prints:
The string "The Racing car.
" was written onto the file "RandomText1.txt
"
但是我希望它仅打印一行:
However I want it to print in just one line:
The string "The Racing car." was written onto the file "RandomText1.txt"
我知道我可以修改字符串以摆脱 null终止符换行符,但我希望有一种可能的方式,在不修改字符串的情况下实现此输出.
I know I can modify the strings to get rid of the null terminator newline but I'd like a way, if possible, to achieve this output without modifying the strings.
有可能吗?
推荐答案
这与null终止符无关. 字符串 必须以空值结尾.
This has nothing to do with the null terminator. a string must be null-terminated.
您在此处遇到尾随换行符(\n
)的问题.您必须先剥离该换行符,然后再将字符串传递给printf()
.
You're facing issues with the trailing newline (\n
) here. you have to strip off that newline before passing the string to printf()
.
Easiest way [requires modification of str
]: You can do this with strcspn()
. Pseudo code:
str[strcspn(str,"\n")] = 0;
(如果可能)在不修改字符串的情况下实现此输出.
是的,也是可能的.在这种情况下,您需要在printf()
中使用length修饰符来限制要打印的数组的长度,例如
Yes, possible, too. In that case, you need to use the length modifier with printf()
to limit the length of the array to be printed, something like,
printf("%15s", str); //counting the ending `.` in str as shown
但是恕我直言,这不是最好的方法,因为必须知道并固定字符串的长度,否则它将无法正常工作.
but IMHO, this is not the best way, as, the length of the string has to be known and fixed, otherwise, it won't work.
一种灵活的情况,
printf("%.*s", n, str);
其中,必须提供n
,并且它需要保留要打印的字符串的长度(没有换行符)
where, n
has to be supplied and it needs to hold the length of the string to be printed, (without the newline)
这篇关于如何在不打印尾随换行符的情况下使用printf打印字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!