簡體   English   中英

用空格讀取C中的文件.txt

[英]Reading a file .txt in C with blank spaces

我試圖用 C 語言打開一個簡單的 txt 文件,如下圖所示。

列表示例

輸入文本:

Name    Sex Age Dad Mom 
Gabriel M   58  George  Claire          
Louise  F   44          
Pablo   M   19  David   Maria

我的疑問是,如何識別列表中的空格並正確跳轉到另一行。

這是我的代碼:

#include <stdio.h>

int main() {
    FILE *cfPtr;

    if ((cfPtr = fopen("clients.txt", "r")) == NULL) {
        puts("The file can't be open");
    } else {
        char name[20];
        char sex[4];
        int age;
        char dad[20];
        char mom[20];
        char line[300];

    printf("%-10s%-10s%-10s%-10s%-10s\n","Name","Sex","Age","Dad","Mom");
    fgets(line,300,cfPtr);
    fscanf(cfPtr,"%10s%10s%d%12s%12s",name,sex,&age,dad,mom);

    while (!feof(cfPtr)) {
        printf("%-10s%-10s%d%12s%12s\n",name,sex,age,dad,mom);
        fscanf(cfPtr,"%19s%3s%d%12s%12s",name,sex,&age,dad,mom);
    }

        fclose(cfPtr);
    }
    return 0;
 }

如果我填寫所有空格,它工作正常......

printf("%-10s%-10s%d%12s%12s\\n",name,sex,age,dad,mom); fscanf(cfPtr,"%19s%3s%d%12s%12s",name,sex,&age,dad,mom);

更改順序為先閱讀,后打印。

理想情況下,文件中的數據應該用逗號、制表符或其他一些字符分隔。 如果數據在固定列中,則將所有內容作為文本(包括整數)讀取,然后將整數轉換為文本。

還要檢查fscanf的返回值,如果結果不是 5,則某些字段丟失。

#include <stdio.h>
#include <string.h>
#include <stdlib.h> 

int main() 
{
    FILE *cfPtr = fopen("clients.txt", "r");
    if(cfPtr == NULL) 
    {
        puts("The file can't be open");
        return 0;
    }

    char name[11], sex[11], dad[11], mom[11], line[300];
    int age;

    fgets(line, sizeof(line), cfPtr); //skip the first line
    while(fgets(line, sizeof(line), cfPtr))
    {
        if(5 == sscanf(line, "%10s%10s%10d%10s%10s", name, sex, &age, dad, mom))
            printf("%s, %s, %d, %s, %s\n", name, sex, age, dad, mom);
    }

    fclose(cfPtr);
    return 0;
}

編輯,將sscan格式更改為直接讀取整數,將緩沖區分配更改為 11,這就是所需要的。

暫無
暫無

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

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