簡體   English   中英

C 從文件中讀取文本並將其放入數組

[英]C Read text from file and put it into array

我正在使用 C 並嘗試從文件中讀取文本並將其存儲在數組中以備后用,但它似乎不起作用。 它也不會給出錯誤。 怎么了?

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

int main(void)
{
    FILE *fp;
    fp = fopen("data.txt", "r");
    char rida[120], str[100];
    int i = 0, j = 0;

    while (fscanf(fp, "%s", str[i]) != EOF)
    {
        rida[i] = str[i];
    }
    fclose(fp);
}

data.txt 文件包含以下內容:

Text
Text2
Text3
Text4
Text5

rida[120] rida[20][120]因為你似乎想單獨存儲每個單詞,所以你需要二維數組。也使用strcpy()復制字符串,而不是賦值運算符=

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

int main(void)
{
    FILE *fp;
    fp = fopen("data.txt", "r");
    char rida[20][120], str[100];
    int i = 0, j = 0;

    while (fscanf(fp, "%s", str) != EOF)
    {
        strcpy(rida[i], str);
        i++;
    }
    size_t n;
    for (n = 0; n < 5; n++) {
        printf("%s\n", rida[n]);
    }
    fclose(fp);
}

在這里,您可以使用命令行參數獲得答案:

int main(int argc,char *argv[])
    {
        FILE *fp;
        if(argc<2) return printf("Error.Not enough arguments.\n"),1;
        if((fp = fopen(argv[1],"r"))==NULL) return printf("Error. Couldn't open the file.\n"),1;
        char str[10][100]={""}; //Making sure to have only the scaned strings in the array
        int i=0;
        while ( fscanf(fp,"%s",str[i++]) != EOF);

        int j=0;
        while(j<i){
        printf("%s\n",str[j++]);
        }

        fclose(fp);
        return 0;
    }

暫無
暫無

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

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