Tia*_*fer 1 c string printf null-terminated
我正在尝试打印一些字符串,printf()但它们是null终止 有尾随换行符和混乱的格式化:
printf("The string \"%s\" was written onto the file \"%s\"", str, fname);
Run Code Online (Sandbox Code Playgroud)
假设字符串包含"The Racing car.",文件名是"RandomText1.txt"
This prints:
The string "The Racing car.
" was written onto the file "RandomText1.txt
"
Run Code Online (Sandbox Code Playgroud)
但是我希望它只用一行打印:
The string "The Racing car." was written onto the file "RandomText1.txt"
Run Code Online (Sandbox Code Playgroud)
我知道我可以修改字符串来摆脱它 null终止符 如果可能的话,我想要一种方法来实现这个输出,而无需修改字符串.
可能吗?
这与null终止符无关.一个字符串 必须是空终止的.
你在\n这里遇到了尾随换行符()的问题.你必须在传递字符串之前剥离该换行符printf().
最简单的方法[ 需要修改str ]:你可以这样做strcspn().伪代码:
str[strcspn(str,"\n")] = 0;
Run Code Online (Sandbox Code Playgroud)
如果可能的话,在不修改字符串的情况下实现此输出.
是的,也可能.在这种情况下,您需要使用长度修改器printf()来限制要打印的数组的长度,例如,
printf("%15s", str); //counting the ending `.` in str as shown
Run Code Online (Sandbox Code Playgroud)
但恕我直言,这不是最好的方法,因为,字符串的长度必须知道和修复,否则,它将无法正常工作.
一个小灵活的案例,
printf("%.*s", n, str);
Run Code Online (Sandbox Code Playgroud)
其中,n必须提供,它需要保持要打印的字符串的长度,(没有换行)
正如已经指出的那样,C中的每个字符串都应该以null结尾(否则 - 怎么printf知道字符串的结束位置?)
你需要在数组中搜索新行,大概是使用strchr.
试试这个:
char* first_newline = strchr(str, '\n');
if (first_newline)
*first_newline = '\0';
Run Code Online (Sandbox Code Playgroud)
它将在换行符的第一个实例处终止字符串.