这真让我抓狂。 我正在尝试从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] = '';
numOfRow++; // This is throwing the error
numOfChar = 0;
}
}
printOutput(rows, numOfRows);
}
如果我注释掉该行,程序将覆盖第一个数组的每一行,并且我只得到最后一句话,因此我知道它正在工作。
我想念什么?
完整的代码在这里:
#include
#include
#define USAGE"USAGE: ./huffman
"
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
", 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] = '';
numOfRow += 1;
numOfChar = 0;
}
}
printOutput(rows, numOfRows);
}
void printOutput(char** matrix, int rows){
for (int i=0; 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.
请显示输入文件示例以及最小的可复制示例。
我认为那正是我所做的? numOfRow初始化为0,并在每次发现句子时在else语句中增加
为什么不使用fgets? 您正在尝试一次读取整行。
我不知道该放什么尺寸...我将如何使用fgets在点之间拆分?
好吧,您可以标记.上返回的那一行...尽管我确实被误解了,所以这样做可能不值得。 至于大小,为什么不1000?
您的countNumOfRows()函数对文件中的点进行计数,然后使用该数字为数组分配空间。 但是,在最后一个点之后和EOF之前可能还有更多的字符(例如CR或LF或CRLF),因此您可以轻松地在已分配内存的末尾进行写入。
尝试:
return (i + 1)
在countNumOfRows()的末尾,看看是否消除了段错误。
错误仍然存在。 我试图分配char **rows = malloc(1000*sizeof(char*));并使用具有2行的txt文件来确定并且错误仍然存在。
你是救星。 谢谢!
最后
以上就是醉熏自行车最近收集整理的关于c语言读入txt多维数据库,将句子从txt文件解析为C语言中的多维数组的全部内容,更多相关c语言读入txt多维数据库,将句子从txt文件解析为C语言中内容请搜索靠谱客的其他文章。
发表评论 取消回复