簡體   English   中英

如何從文本文件中讀取特殊字符?

[英]How to read special characters from a text file?

我有一個帶有一些特殊字符( \n\t等)的文本文件。 問題是:無論如何打印一個新行或一個制表符,而不是只打印字符串\n\t

int main(){

    char line[10];

    FILE*file= fopen("file.txt", "r"); // txt content => "line 1 \n line 2 \n line 3"
    if (file != NULL){
        while (fgets(line, 10, file) != NULL)
            printf("%s", line);
    }
    return 0;
}

稱之為 function:

void cleanUp(char * line) {
    int x;
    int y = 0;
    for (x = 0; x < strlen(line) - 1; x++) {
        if (line[x] == '\\') {
            if (line[x + 1] == 'n') {
                line[y++] = '\n';
                x = x + 2; /* if there is always a space after the \n otherwise x++ */
                continue;
            }
            if (line[x + 1] == 't') {
                line[y++] = '\t';
                x = x + 2; /* if there is always a space after the \t otherwise x++ */
                continue;
            }
        }
        line[y++] = line[x];
    }
    line[y++] = '\n';
    line[y] = '\0';
}

印刷前。

暫無
暫無

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

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