Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

c - How to print from a text file into a 2D array using fgets?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Including libraries to be used

int readMovies(FILE *file, char Names[3][50]) {

  int i;
  int j;

  FILE *file = fopen("Names.txt", "r")
  if (myFile == NULL) {
      printf("Error");
      exit(-1);
  }
  for(i = 0; i < 3; i++) {
    for(j = 0; j < 3; j++) {
      fgets(Names[i][j], 50, file);
    }
  }

}

I'm trying to print from the attached file into the array called, "Names." My first thought was using fgets, but I'm confused on how to do it if this is even the best way. How do I use fgets to populate the array in the above function?

The file name is "Names.txt", and has the following content, not ignoring the numbering:

  1. charlie
  2. scarlett Johansson
  3. saint nicholas santa claus

This is the information I want to use fgets (not including the numbering) into the array called Names[3][50], how do I do that?

question from:https://stackoverflow.com/questions/65895049/how-to-print-from-a-text-file-into-a-2d-array-using-fgets

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well you I understand that you are dealing with an array of strings, if so each string can hold up to 48 characters, (49 if you get rid of the ' ' fgets() adds). This should work:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define MAX_LEN 50
#define MAX_LINES 3


int readMovies(FILE *file, char Names[3][50]) {

  int i;

  FILE *file = fopen("Names.txt", "r")
  if (myFile == NULL) {
      printf("Error");
      exit(-1);
  }
  for(i = 0; i < MAX_LINES; i++) {
    fgets(Names[i],MAX_LEN, file);
  }
/* ... */
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...