c - 如何打印包含 \n 字符的字符串?
问题描述
假设我们有char* str = "Hello world!\n"
. 显然,当您打印此内容时,您会看到Hello world!
,但我想让它打印出来Hello world!\n
。有没有办法打印包含换行符的字符串?
编辑:我想打印Hello world!\n
而不更改字符串本身。显然我可以做到char* str = "Hello world \\n"
。
另外,我问这个问题的原因是因为我正在使用 fopen 打开一个带有大量换行符的 txt 文件。将文件制作成字符串后,我想通过每个换行符拆分字符串,以便我可以单独修改每一行。
解决方案
我认为这是 XY 问题的典型案例:您询问特定解决方案而没有真正关注原始问题。
将文件制作成字符串后
为什么你认为你需要一次读取整个文件?这通常不是必需的。
我想通过每个换行符拆分字符串,以便我可以单独修改每一行。
你不需要打印字符串来做到这一点(你想要“让它打印出来Hello World!\n
)。你不需要修改字符串。你只需要逐行阅读它!这fgets
就是:
void printFile(void)
{
FILE *file = fopen("myfile.txt", "r");
if (file) {
char linebuf[1024];
int lineno = 1;
while (fgets(linebuf, sizeof(linebuf), file)) {
// here, linebuf contains each line
char *end = linebuf + strlen(linebuf) - 1;
if (*end == '\n')
*end = '\0'; // remove the '\n'
printf("%5d:%s\\n\n", lineno ++, linebuf);
}
fclose(file);
}
}
我想做它,所以它会打印
Hello world!\n
如果您真的想这样做,则必须将 ASCII LF(即\n
代表)转换为\n
输出,例如:
#include <stdio.h>
#include <string.h>
void fprintWithEscapes(FILE *file, const char *str)
{
const char *cr;
while ((cr = strchr(str, '\n'))) {
fprintf(file, "%.*s\\n", (int)(cr - str), str);
str = cr + 1;
}
if (*str) fprintf(file, "%s", str);
}
int main() {
fprintWithEscapes(stdout, "Hello, world!\nA lot is going on.\n");
fprintWithEscapes(stdout, "\nAnd a bit more...");
fprintf(stdout, "\n");
}
输出:
Hello, world!\nA lot is going on.\n\nAnd a bit more...
推荐阅读
- c++ - 如何使用 QSqlQuery 和 SQLite 从新插入的行中获取 ID?
- python - 导航 HTML 标签以从锚定标签中提取文本
- java - 在文本字段上键入后如何隐藏 EditText 错误?
- java - 使用结束条件限制 MSC01-J (SonarQube) 计算有限的 while 循环花费了多少时间
- excel - 如何修复 Excel VBA 中的“运行时错误‘380’?
- ruby-on-rails - Capybara Selenium with Javascript fetch 因未经授权而失败
- android-studio - 无法将 Android Studio 更新到 3.4.1
- c# - 根据其他两列中的值旋转一列中的行值
- powershell - 有没有办法在同一个批处理函数中捕获文件路径和名称?
- json - 使用 ForkJoin 同时从 2 个 API 访问数据:未定义错误