簡體   English   中英

從文件中讀取字符串和整數列

[英]Reading columns of strings and integers from file

我能夠從單獨的文件中讀取字符,單詞,句子和整數,但是我正努力從同一文件中讀取單詞和整數。 假設我的文件包含以下內容:

Patrice 95
Rio 96
Marcus 78
Wayne 69
Alex 67
Chris 100
Nemanja 78

到目前為止,我的部分解決方案(讀取字符串)是使用fgetc()並檢查文本文件中的空格和/或回車符以將名稱與數字分開。

fgetc的主要問題是它逐個字符地讀取,因此整數並不意味着要這樣讀取。 作為一種解決方法,每當讀入數字時,我都會將字符轉換為整數。

這是主要的代碼結構:

typedef struct person {
    char name[10][10];
    char surname[10][10];
    int age [10];
} person_t;

FILE *inp; /* pointer to input file */
char c;
int word_count = 0;
int char_count = 0;
int i = 0;
int x;
person_t my_person;

while ((c = fgetc(inp)) != EOF) {
        if (c == ' ' || c == '\r') {
            printf("\n");

            my_person.name[word_count][char_count] = '\0'; //Terminate the string
            char_count = 0; //Reset the counter.
            word_count++;
        }
        else {

            if (c >= '0' && c <= '9') {
                x = c - '0'; //converting to int
                my_person.age[i] = x;
                printf("%d", my_person.age[i]);
                i++;
            }
            else {
                my_person.name[word_count][char_count] = c; 
                printf("%c",my_person.name[word_count][char_count]);

                if (char_count < 19) {
                    char_count++;
                }
                else {
                    char_count = 0;
                }
            }
        }   
    }
}


for (int i = 0; i<7; i++) {
    printf("ages: %d \n",my_person.age[i] );  //never executes
}

樣本輸出:

Patrice
95

Rio
96

Marcus
78

Wayne
69

Alex
67

Chris

完整的代碼可以在pastebin上找到。

為什么for循環永遠不會執行? 關於我可以改進以讀取字符串和整數列的任何建議?

使用fgets()讀取整行。

char line[100];
while (fgets(line, sizeof line, inp)) {
    // got a line, need to isolate parts
}

然后,根據單詞是否可以嵌入空格來選擇以下策略之一。

a) sscanf()隔離名稱和年齡

while (fgets(line, sizeof line, inp)) {
    char name[30];
    int age;
    if (sscanf(line, "%29s%d", name, &age) != 2) /* error, bad line */;
    // ...
}

b) strrchr()查找最后一個空格,然后進行字符串操作以提取名稱和年齡。

while (fgets(line, sizeof line, inp)) {
    char name[30];
    int age;
    char *space = strrchr(line, ' ');
    if (!space) /* error, bad line */;
    if (space - line >= 30) /* error, name too long */;
    sprintf(name, "%.*s", space - line, line);
    age = strtol(space, NULL, 10); // needs error checking
    // ...
}

策略b)在https://ideone.com/ZOLie9上

暫無
暫無

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

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