简体   繁体   English

将文件读入二维数组

[英]Read a file to a 2D array

I'm new in C and trying to put a text file into a 2D array.我是 C 新手,试图将文本文件放入二维数组中。 For example: Text file content: When, in the course of human events, it becomes necessary dark like To put it in the 2D array like this: when, in the course ...例如: 文本文件内容:当,在人类事件的过程中,它变得有必要像这样把它放在二维数组中:当,在过程中......

However, it works fine for the first word, which is "when,", is stored in the 2D array then the rest is just like in the picture.但是,它适用于第一个单词,即“何时”,存储在 2D 数组中,然后其余的就像图片中一样。

enter image description here在此处输入图片说明

Could you help me to figure out what went wrong please?你能帮我弄清楚出了什么问题吗? Here is my code:这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#define SIZE 100
#define ROWS 5000
#define COLS 50

int readFile(char text[ROWS][COLS]);
void menu(char* choice);

int main() {
    int numWords = 0,valid,readFileFirst = 0,i;
    char *text,choice;
    text = (char*)malloc((ROWS*COLS)*sizeof(char));
    numWords = readFile(text);
}

int readFile(char text[][COLS]) {
FILE *keyFile;
char fileInput[SIZE],inBuf[SIZE],ch;
int i = 0, j = 0;
int numWords = 1;
int valid = 0;

printf("Enter the file to use as a key\n");
fgets(inBuf,SIZE,stdin);
sscanf(inBuf,"%s",fileInput);

keyFile = fopen(fileInput,"r");

if(keyFile == NULL) {
    printf("Error! Find Not Found");
}

else {
    while((ch = fgetc(keyFile)) != EOF) {
        if(ch == ' ' || ch == '\n' || ch == '\r' || ch == '\0') {
            numWords++;
            i++;
            j = 0;
        }
        
        else {
            text[i][j] = tolower((unsigned char)ch);
            j++;
        }
    }
}

printf("Number of words in this file is %d\n", numWords);
printf("%c\n", text[2][1]);
return numWords;
}
  1. solution:解决方案:

change改变

char*text;

text = (char*)malloc((ROWS*COLS)*sizeof(char));

to

char text[COLS][ROWS];
  1. solution解决方案

if you want to use malloc() you need a pointer char **ptr which is a pointer to a char *pointer wich points to char如果你想使用malloc()你需要一个指针char **ptr它是一个指向char *pointer指向char

char **text = malloc( COLS * sizeof(char*));
for( int i = 0; i < COLS; ++i )
{
  text[i] = malloc( ROWS * sizeof( char ));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM