如何正确null终止c字符串?

时间:2013-06-04 08:28:42

标签: 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

1 个答案:

答案 0 :(得分:3)

看起来您不能保证NUMBER_OF_WORDSuniqueWords中有wordCount个条目,但您最后会打印出很多条目。无论是否对您所看到的输出负责,如果您的输入的单词少于NUMBER_OF_WORDS,则可能会产生此类输出。