簡體   English   中英

將txt文件中的詞句解析為C中的多維數組

[英]Parsing senteces from a txt file to a multidimensional array in C

這真讓我抓狂。 我正在嘗試從txt文件中解析每個句子(即點之間的所有字符),並將每個句子插入數組。 最終目標是擁有一個多維數組,每個句子作為單個數組。 我設法達到了我認為應該可以工作的程度,但是我從numOfRow++行遇到了分段錯誤(核心轉儲)錯誤

void parseRows(FILE* file){
    int c;
    int numOfRow = 0;
    int numOfChar = 0;
    int numOfRows = countNumOfRows(file);
    fseek(file, 0, SEEK_SET); // Reset file pointer position to the beginning
    char **rows = malloc(numOfRows*sizeof(char*));
    for (int i=0; i < numOfRows; i++) rows[i] = malloc(1000*sizeof(char));

    while ((c=fgetc(file))!= EOF) {   
        if (c != '.') {
            rows[numOfRow][numOfChar] = c;
            numOfChar++;
        } else {
            rows[numOfRow][numOfChar] = '\0';
            numOfRow++;       // This is throwing the error              
            numOfChar = 0;            
        }
    }
    printOutput(rows, numOfRows);
}

如果我注釋掉該行,程序將覆蓋第一個數組的每一行,並且我只得到最后一句話,因此我知道它正在工作。 我想念什么?

完整的代碼在這里:

#include <stdio.h>
#include <stdlib.h>
#define USAGE "USAGE: ./huffman <textFile.txt>\n"

FILE* openFile(char[]);
void parseRows(FILE*);
int countNumOfRows(FILE*);
void printOutput(char**, int);

int main(int argc, char** argv){
    FILE* fd;
    if (argc != 2) printf("%s", USAGE);

    fd = openFile(argv[1]);
    parseRows(fd);
}

FILE* openFile(char* file){
    FILE* stream;
    stream = fopen(file, "r");
    return stream;
}

int countNumOfRows(FILE* file){
    int i = 0;
    char c;
    while ((c=fgetc(file))!= EOF) {   
        if (c == '.') i++;
    }
    printf("numero di righe %d\n", i);
    return i;
}

void parseRows(FILE* file){
    int c;
    int numOfRow = 0;
    int numOfChar = 0;
    int numOfRows = countNumOfRows(file);
    fseek(file, 0, SEEK_SET); // Reset file pointer position to the beginning
    char **rows = malloc(numOfRows*sizeof(char*));
    for (int i=0; i < numOfRows; i++) rows[i] = malloc(1000*sizeof(char));

    while ((c=fgetc(file))!= EOF) {   
        if (c != '.') {
            rows[numOfRow][numOfChar] = (char)c;
            numOfChar++;
        } else {
            rows[numOfRow][numOfChar] = '\0';    
            numOfRow += 1;               
            numOfChar = 0;            
        }
    }
    printOutput(rows, numOfRows);
}

void printOutput(char** matrix, int rows){
    for (int i=0; i<rows; i++){
        printf("%s", matrix[i]);
    }
}

輸入文件textFile.txt的示例:

Any text that contains more than one sentence.
This Should get parsed and return a 2 dimension array with every sentence as single array.

您的countNumOfRows()函數對文件中的點進行計數,然后使用該數字為數組分配空間。 但是,在最后一個點之后和EOF之前可能還有更多的字符(例如CR或LF或CRLF),因此您可以輕松地在已分配內存的末尾進行寫入。

嘗試:

return (i + 1)

在countNumOfRows()的末尾,看看是否消除了段錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM