簡體   English   中英

C:如何使fget從文件中讀取\\ n換行符?

[英]C: How to make fgets read a \n line break from a file?

我有一個程序(控制台),將所有文本放在單獨的.txt文件中。

我使用fgets()從文件中讀取字符串,但是當文件包含\\ n並稍后打印該字符串時,它將打印\\ n而不是換行符

這是一個例子:

FILE* fic = NULL;
char str[22]; //str is the string we will use

//open the file
fic = fopen ("text.txt", "r");

//read from the file
fgets(str, size, fic);

printf(str);

如果這是我的text.txt中的內容:

This is \n an example

但是,控制台上顯示的是

This is \n an example

代替

This is 
 an example

編輯:在文件中,其寫為​​\\ n。 我也嘗試在文件中使用addint \\或\\ t,但是它將打印\\和\\ t而不是列表或單個反斜杠

fgets只是將\\和n視為普通字符。 您必須自行將其轉換為換行符。 也許借助strstr()或類似方法。

這是因為編譯器在解析代碼時會處理字符串和字符文字中的轉義字符。 庫或所有字符串的運行時代碼中都不存在它。

例如,如果要翻譯從文件中讀取的兩個字符\\n ,則需要在代碼中自行處理。 例如,通過逐個字符遍歷字符串並查找'\\\\'后跟'n'

編譯器正在掃描文本文件,並將數據/文本按原樣存儲在str字符串中。 編譯器不將\\n用作轉義序列。 因此,如果想在出現\\n時轉到下一行,則應該逐字符進行掃描,如果出現\\n ,則應該使用printf("\\n")

#include <stdio.h>

int main(){
    char str[30];
    int i = 0;
    FILE *fic = NULL;
    fic = fopen("text.txt", "r");
    while(!feof(fic)){
        str[i++] = getc(fic);
        if(i > 30){    //Exit the loop to avoid writing outside of the string
            break;
        }
    }
    str[i - 1] = '\0';
    fclose(fic);

    for(i = 0; str[i] != '\0'; i++){
        if(str[i] == 'n' && str[i - 1] == '\\'){
            printf("\n");
            continue;
        }
        if(str[i] == '\\' && str[i + 1] == 'n'){
            printf("\n");
            continue;
        }
        printf("%c",str[i]);
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM