首页 > 解决方案 > 如何打印包含 \n 字符的字符串?

问题描述

假设我们有char* str = "Hello world!\n". 显然,当您打印此内容时,您会看到Hello world!,但我想让它打印出来Hello world!\n。有没有办法打印包含换行符的字符串?

编辑:我想打印Hello world!\n而不更改字符串本身。显然我可以做到char* str = "Hello world \\n"

另外,我问这个问题的原因是因为我正在使用 fopen 打开一个带有大量换行符的 txt 文件。将文件制作成字符串后,我想通过每个换行符拆分字符串,以便我可以单独修改每一行。

标签: cprintfline-breaks

解决方案


我认为这是 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...

推荐阅读