簡體   English   中英

如何使用 fscanf 讀取包含多個單詞的文本文件並通過索引將它們存儲到字符串數組中

[英]How to use fscanf to read a text file including many words and store them into a string array by index

wordlist.txt 包括:

able
army
bird
boring
sing
song

我想使用 fscanf() 逐行讀取這個 txt 文件,並通過索引每個單詞將它們存儲到一個字符串數組中,如下所示:

src = [able army bird boring sing song]

其中 src[0]= "able", src[1] = "army" 等等。 但我的代碼只輸出 src[0] = "a", src[1] = "b" ... 有人能幫我弄清楚我的代碼出了什么問題:

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

int main(int argc, char *argv[])
{
    FILE *fp = fopen("wordlist.txt", "r");
    if (fp == NULL)
    {
        printf("%s", "File open error");
        return 0;
    }
    char src[1000];
    for (int i = 0; i < sizeof(src); i++)
    {
        fscanf(fp, "%[^EOF]", &src[i]);
    }
    fclose(fp);
    printf("%c", src[0]);
    getchar();
    return 0;
}

相當贊賞!

例如像這樣。

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

#define MAX_ARRAY_SIZE 1000
#define MAX_STRING_SIZE 100

int main(int argc, char *argv[]) {
    FILE *fp = fopen("wordlist.txt", "r");
    if (fp == NULL) {
        printf("File open error\n");
        return 1;
    }
    char arr[MAX_ARRAY_SIZE][MAX_STRING_SIZE];
    int index = 0;
    while (1) {
        int ret = fscanf(fp, "%s", arr[index]);
        if (ret == EOF) break;
        ++index;
        if (index == MAX_ARRAY_SIZE) break;
    }
    fclose(fp);
    for (int i = 0; i < index; ++i) {
        printf("%s\n", arr[i]);
    }
    getchar();
    return 0;
}

一些注意事項:

  • 如果有錯誤,最好返回 1 而不是 0,因為 0 表示執行成功。
  • 對於字符數組,您使用指針。 對於字符串數組,您使用雙指針。 習慣它們有點棘手,但它們很方便。
  • 此外,檢查 fscanf 的返回值會很棒。
  • 對於固定大小的數組,使用#define定義大小很有用,以便以后在代碼中多次使用時更容易更改。

它一次讀取一個字符,它本身的大小為 4,就像我們在 word 中看到的 sizeof('a') 一樣。 'b' 等也是如此。 因此,您可以使用的一種方法是不斷檢查何時有空格或換行符,以便我們可以將這兩件事之前的數據保存為一個單詞,然后通過在它們之間添加空格並將它們連接起來來組合這些小數組以獲得單個大批。

暫無
暫無

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

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