下面的代码计算文本文档中每个唯一术语的出现次数。我相信我用'\0'
正确地终止了每个c字符串
#include <stdio.h>
#include <string.h>
int main ()
{
int c;
FILE *file;
int NUMBER_OF_WORDS = 100;
int MAX_WORD_LENGTH = 30;
char uniqueWords[NUMBER_OF_WORDS][MAX_WORD_LENGTH+1];
int wordCount[NUMBER_OF_WORDS];
int uniqueWordIndex =0;
char tempWord[MAX_WORD_LENGTH+1];
int tempWordIndex = 0;
file = fopen("sample.txt", "r");
if (file) {
while ((c = getc(file)) != EOF && uniqueWordIndex < 100){
if( isalpha(c)){
tempWord[tempWordIndex] = c;
tempWordIndex++;
}else if ( (c == ' ' || c == '\n') && strlen(tempWord) > 0 ) {
tempWord[tempWordIndex] = '\0';
int k = 0;
int newUnique = 1;
for (k=0; k<NUMBER_OF_WORDS; k++){
if (strcmp (tempWord, uniqueWords[k]) == 0){
wordCount[k]++;
newUnique = 0;
break;
}
}
if (newUnique){
int i=0;
wordCount[uniqueWordIndex] = 1;
for (i=0; i<strlen(tempWord); i++)
uniqueWords[uniqueWordIndex][i] = tempWord[i];
uniqueWords[uniqueWordIndex][i] = '\0';
uniqueWordIndex++;
}
tempWordIndex = 0;
}
}
int i =0;
for (i =0; i< NUMBER_OF_WORDS; i++){
int k = 0;
for (k =0; k< strlen(uniqueWords[i]); k++)
printf("%c",uniqueWords[i][k]);
printf(" %d\n", wordCount[i]);
}
fclose(file);
}
return(0);
}
有没有语法错误导致这种古怪的输出?
term 2
something 5
reading 1
level 1
!J<8F><FF>^? 0
<C8>B~8<91>^? 0
最佳答案
看起来您不能保证在NUMBER_OF_WORDS
或uniqueWords
中有wordCount
条目,但是您在最后打印出了这么多条目。不管这是否是你看到的输出的原因,如果你输入的单词少于NUMBER_OF_WORDS
个,它很可能会产生这样的输出。
关于c - 如何正确使null终止c字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16913068/