如何打印包含 \n 字符的字符串?

How to print a string with its \n characters included?

假设我们有 char* str = "Hello world!\n"。很明显,当你打印这个时你会看到 Hello world!,但我想打印它所以它会打印 Hello world!\n。有什么方法可以打印包含换行符的字符串吗?

编辑:我想在不更改字符串本身的情况下打印 Hello world!\n。显然我可以做 char* str = "Hello world \n".

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

我认为这是 XY 问题的典型案例:您询问特定的解决方案而没有首先真正关注原始问题。

After making the file into a string

为什么你认为你需要一次读入整个文件?这通常是不必要的。

I want to split the string by each of its line breaks so I can modify each line individually.

你不需要打印字符串来做到这一点(你想要“让它打印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 = '[=10=]'; // remove the '\n'
            printf("%5d:%s\n\n", lineno ++, linebuf);
        }
        fclose(file);
    }
}

I want to make it so it will print 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...