2016-05-10 13 views
-1

私はCを使っていて、ファイルからテキストを読み込み、後で使うために配列に格納しようとしていますが、うまくいかないようです。また、エラーは発生しません。なにが問題ですか?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 
+1

'str [i]'、本当に?あなたのコンパイラはあなたに何を伝えましたか? –

+0

個々の文字と文字列(文字の配列)が混ざり合っています。 – lurker

+0

どうすればいいですか? – Miner123

答えて

1

変更rida[120]rida[20][120]のようなものに、あなたが自分自身で各単語を格納したいと思われるので、あなたは、2次元array.Also使用を必要とするので、あなたはCOMMを使って答えを持っている。ここ

#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); 
} 
+0

が返ってくる可能性があります。とにかく正解+1 :) – Cherubim

0

:代入演算子=を文字列をコピーし、しないようにstrcpy()行引数:

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; 
    } 
関連する問題