更新时间:2022-11-03 22:14:40
这与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)