C fscanf 意外地从下一行中提取内容
C fscanf unexpectedly pulling content from next line
编辑:好的,我发现了令人尴尬的错误。我的描述数组对于那一行来说不够大...
我试图从一个简单格式的文本文件中提取相关的缩写和描述,但我 运行 只在一行上遇到了问题,而其他每一行都可以正常工作。
在我正在阅读的文本文件中,第 5-7 行是:
5. FW Foreign word
6. IN Preposition or subordinating conjunction
7. JJ Adjective
我试图对每一行做的是读取缩写并将其存储为字符数组,然后对描述执行相同的操作。对于除#6 之外的每一行,它都工作正常。
我期望的是:
print decription[line6] => "Preposition or subordinating conjunction"
但我得到的是:
print decription[line6] => "Preposition or subordinating conjunctio"Adjective"
我很不明白为什么它会那样做。它似乎正在从下一行读取数据。或者也许我最终将下一行覆盖到该数组中。
#include <stdio.h>
int main(){
FILE *fileToRead = fopen("PennTreebank_POS_Tags.txt", "r");
FILE *fileToWrite = fopen("newFile.txt", "w");
int i, j;
i = j = 0;
int nextChar;
char abbreviation[50][5];
char description[50][40];
while( fscanf(fileToRead, "%*s %s ", abbreviation[i]) != EOF ){
description[i][0] = '"';
while( ((nextChar = fgetc(fileToRead)) != '\n') && (nextChar != EOF) ){
description[i][j] = nextChar;
j++;
}
description[i][j] = '"';
description[i][j+1] = '[=13=]';
j=1;
i++;
}
for( i=0; i<36; i++ ){
printf("%s %s\n", abbreviation[i], description[i]);
}
}
文本 "Preposition or subordinating conjunction" 的长度为 40 个字符。
所以数组
char description[50][40];
将不足以容纳长度 40 加上 0 终止符。
编辑:好的,我发现了令人尴尬的错误。我的描述数组对于那一行来说不够大...
我试图从一个简单格式的文本文件中提取相关的缩写和描述,但我 运行 只在一行上遇到了问题,而其他每一行都可以正常工作。
在我正在阅读的文本文件中,第 5-7 行是:
5. FW Foreign word
6. IN Preposition or subordinating conjunction
7. JJ Adjective
我试图对每一行做的是读取缩写并将其存储为字符数组,然后对描述执行相同的操作。对于除#6 之外的每一行,它都工作正常。
我期望的是:
print decription[line6] => "Preposition or subordinating conjunction"
但我得到的是:
print decription[line6] => "Preposition or subordinating conjunctio"Adjective"
我很不明白为什么它会那样做。它似乎正在从下一行读取数据。或者也许我最终将下一行覆盖到该数组中。
#include <stdio.h>
int main(){
FILE *fileToRead = fopen("PennTreebank_POS_Tags.txt", "r");
FILE *fileToWrite = fopen("newFile.txt", "w");
int i, j;
i = j = 0;
int nextChar;
char abbreviation[50][5];
char description[50][40];
while( fscanf(fileToRead, "%*s %s ", abbreviation[i]) != EOF ){
description[i][0] = '"';
while( ((nextChar = fgetc(fileToRead)) != '\n') && (nextChar != EOF) ){
description[i][j] = nextChar;
j++;
}
description[i][j] = '"';
description[i][j+1] = '[=13=]';
j=1;
i++;
}
for( i=0; i<36; i++ ){
printf("%s %s\n", abbreviation[i], description[i]);
}
}
文本 "Preposition or subordinating conjunction" 的长度为 40 个字符。
所以数组
char description[50][40];
将不足以容纳长度 40 加上 0 终止符。