簡體   English   中英

將文件讀入二維數組

[英]Read a file to a 2D array

我是 C 新手,試圖將文本文件放入二維數組中。 例如: 文本文件內容:當,在人類事件的過程中,它變得有必要像這樣把它放在二維數組中:當,在過程中......

但是,它適用於第一個單詞,即“何時”,存儲在 2D 數組中,然后其余的就像圖片中一樣。

在此處輸入圖片說明

你能幫我弄清楚出了什么問題嗎? 這是我的代碼:

#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. 解決方案:

改變

char*text;

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

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

如果你想使用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