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"
这打印:
The string "The Racing car.
" was written onto the file "RandomText1.txt
"
不过我希望它只打印一行:
The string "The Racing car." was written onto the file "RandomText1.txt"
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.
是否可以?
这与空终止符无关。 Astring must以空终止。
您遇到了尾随换行符的问题 (\n
) 这里。你必须剥离将字符串传递给之前的换行符printf()
.
最简单的方法[需要修改str
]:你可以这样做strcspn() http://linux.die.net/man/3/strspn。伪代码:
str[strcspn(str,"\n")] = 0;
如果可能,在不修改字符串的情况下实现此输出。
是的,也有可能。在这种情况下,您需要使用长度修饰符printf()
限制要打印的数组的长度,例如,
printf("%15s", str); //counting the ending `.` in str as shown
但恕我直言,这不是最好的方法,因为字符串的长度必须已知并固定,否则它将无法工作。
有点灵活的情况下,
printf("%.*s", n, str);
where, n
必须提供并且需要保存要打印的字符串的长度(没有换行符)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)