如何使用 printf 打印字符串而不打印尾随换行符
How to print a string using printf without it printing the trailing newline
我正在尝试使用 printf()
打印一些字符串,但它们是 null 终止的 具有尾随换行符并且与格式混淆:
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"
我知道我可以修改字符串以摆脱 空终止符 换行符,但如果可能的话,我想要一种方法来实现此输出而无需修改字符串。
可能吗?
编辑:看看这个 ;)
How to print only certain parts of a string?
您只需打印 'strings lenths - 1' 个字符
这与空终止符无关。 字符串 必须以null结尾。
您在此处遇到尾随换行符 (\n
) 的问题。在将字符串传递给 printf()
.
之前,您必须 去掉 那个换行符
最简单的方法[需要修改 str
]:您可以使用 strcspn()
来完成此操作。伪代码:
str[strcspn(str,"\n")] = 0;
if possible, to achieve this output without modifying the strings.
是的,也有可能。在这种情况下,您需要使用带有 printf()
的长度修饰符来限制要打印的数组的长度,例如
printf("%15s", str); //counting the ending `.` in str as shown
但是恕我直言,这不是最好的方法,因为字符串的长度必须已知并固定,否则将无法工作。
稍微灵活一点,
printf("%.*s", n, str);
其中,必须提供 n
并且它需要保存要打印的字符串的长度,(没有换行符)
正如已经指出的那样,C 中的每个字符串都应该以 null 结尾(否则 - printf
怎么知道字符串在哪里结束?)
您需要在数组中搜索换行符,大概使用 strchr。
试试这个:
char* first_newline = strchr(str, '\n');
if (first_newline)
*first_newline = '[=10=]';
它将在第一个换行符处终止字符串。
您似乎使用标准函数 fgets
(或其他方法)读取数组 str
中的数据,该函数在字符串中还包含对应的换行符 '\n'
输入密钥。
你应该删除这个字符。这可以通过以下方式完成
size_t n = strlen( str );
if ( n && str[n-1] == '\n' ) str[n-1] = '[=10=]';
我正在尝试使用 printf()
打印一些字符串,但它们是 null 终止的 具有尾随换行符并且与格式混淆:
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"
我知道我可以修改字符串以摆脱 空终止符 换行符,但如果可能的话,我想要一种方法来实现此输出而无需修改字符串。
可能吗?
编辑:看看这个 ;)
How to print only certain parts of a string?
您只需打印 'strings lenths - 1' 个字符
这与空终止符无关。 字符串 必须以null结尾。
您在此处遇到尾随换行符 (\n
) 的问题。在将字符串传递给 printf()
.
最简单的方法[需要修改 str
]:您可以使用 strcspn()
来完成此操作。伪代码:
str[strcspn(str,"\n")] = 0;
if possible, to achieve this output without modifying the strings.
是的,也有可能。在这种情况下,您需要使用带有 printf()
的长度修饰符来限制要打印的数组的长度,例如
printf("%15s", str); //counting the ending `.` in str as shown
但是恕我直言,这不是最好的方法,因为字符串的长度必须已知并固定,否则将无法工作。
稍微灵活一点,
printf("%.*s", n, str);
其中,必须提供 n
并且它需要保存要打印的字符串的长度,(没有换行符)
正如已经指出的那样,C 中的每个字符串都应该以 null 结尾(否则 - printf
怎么知道字符串在哪里结束?)
您需要在数组中搜索换行符,大概使用 strchr。
试试这个:
char* first_newline = strchr(str, '\n');
if (first_newline)
*first_newline = '[=10=]';
它将在第一个换行符处终止字符串。
您似乎使用标准函数 fgets
(或其他方法)读取数组 str
中的数据,该函数在字符串中还包含对应的换行符 '\n'
输入密钥。
你应该删除这个字符。这可以通过以下方式完成
size_t n = strlen( str );
if ( n && str[n-1] == '\n' ) str[n-1] = '[=10=]';