0

Hey there, How do I go about copying text inside a text file into a multidimensional character array?

supposing the text file( text_file.txt) contained

this is the first line

this is the second line

this is the third line

#include <stdio.h>
int main(void){
 FILE *f;
 f=fopen("text_file.txt","r");
 if (f==NULL){
  printf("invalid!");
  return 1;
  }
 else {
  printf("successful");
  }

 char copied_text[80][80];

 while (!feof(f)){
  int i=0,j=0;
  fgets(copied_text[i][j],"%s",f);
  i++;
  }

 return 0;
}

-thank you.

4

1 に答える 1

1

あなたのコードはほとんど機能すると思います。
int i の宣言をループの外に移動するだけです。
ここでポインタが必要なため、fgets の最初のパラメータをcopyed_text[i]に変更します。
fgets の 2 番目のパラメータを 80 に変更します。これは、許容可能な文字列の長さを示す int にする必要があるためです。

#include <stdio.h>
int main(void){
    FILE *f;
    f=fopen("text_file.txt","r");
    if (f==NULL){
        printf("invalid!\n");
        return 1;
    }
    else {
        printf("successful\n");
    }

    char copied_text[80][80];

    int i=0;
    while (!feof(f)){
        fgets(copied_text[i],80,f);
        ++i;
    }

    for(int i = 0; i <3; ++i)
        printf("%s\n", copied_text[i]);
    return 0;
}
于 2009-11-30T07:18:13.580 に答える