好的。所以我正在读取文本文件中的文本并将其存储到 char 数组中,这是按预期工作的。但是,文本文件包含许多换行转义序列。那么问题是,当我用存储的文本打印出字符串数组时,它会忽略这些换行符序列并简单地将它们打印为“\n”。
这是我的代码:
char *strings[100];
void readAndStore(FILE *file) {
int count = 0;
char buffer[250];
while(!feof(file)) {
char *readLine = fgets(buffer, sizeof(buffer), file);
if(readLine) {
strings[count] = malloc(sizeof(buffer));
strcpy(strings[count], buffer);
++count;
}
}
}
int main() {
FILE *file1 = fopen("txts", "r");
readAndStore(&*file1);
printf("%s\n", strings[0]);
printf("%s\n", strings[1]);
return 0;
}
输出变成这样:
Lots of text here \n More text that should be on a new line, but isn't \n And so \n on and and on \n
有什么方法可以让它将“\n”读取为实际的换行符转义序列,还是我只需要将它们从我的文本文件中删除并找出其他方法来分隔我的文本?
最佳答案
没有。事实上,\n
是您的编译器的一个特殊转义序列,它将它转换为单个字 rune 字,即“LF”(换行,返回),具有 ASCII 代码 0x0A
。因此,编译器赋予了该序列特殊的含义。
相反,当从文件读取时,\n
被读取为两个不同的字符,ASCII 代码 0x5c,0x6e
。
您需要编写一个例程来替换所有出现的 \\n
(由字符\和 n 组成的字符串,双重转义是必要的,以告诉编译器不要将其解释为转义序列)与 \n
(单个转义序列,表示换行)。
关于c - 使用 '/n' 从文本文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19343994/