0
我有以下代碼來計算文本文檔中每個唯一術語的出現次數。我相信我正確端接每個C字符串'\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
此輸出與給定的代碼不匹配。是否有其他要告訴我們的內容? –
你是否通過'gdb'運行你的代碼?如果不是,爲什麼不呢?像這樣的問題是調試器是爲... – Will
爲什麼你可以使用'printf','strlen'和'strcmp'而不是'scanf'或'strcpy'?這似乎是*爲我使用了錯誤的工具*的例子。 – Sebivor