我要打印一个文本文件的所有单词及其计数。当它第二次读取相同的单词时,它会输出数字零。我不知道如何输出正确的值。例如,如果它找到“and”,它将打印“and: 1”,但是当它再次找到“and”时,它会打印“and: 0”。
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "hashMap.h"
int main (int argc, const char * argv[]){
char* word;
int *value = 0;
const char* filename;
struct hashMap *hashTable;
int tableSize = 10;
clock_t timer;
FILE *fileptr;
if(argc == 2)
filename = argv[1];
else
filename = "input1.txt"; /*specify your input text file here*/
printf("opening file: %s\n", filename);
fileptr = fopen(filename, "r");
if(fileptr != 0){
printf("Open Successfull!\n");
}
else{
printf("Failed to open!\n");
}
timer = clock();
hashTable = createMap(tableSize);
/*... concordance code goes here ...*/
while(1){
word = getWord(fileptr);
if(word == NULL){
break;
}
value = (int*)atMap(hashTable, word);
if(value != NULL){
value++;
}
else{
value = (int *) malloc(sizeof(int));
*value = 1;
insertMap(hashTable, word, value);
}
printf("%s:%d\n", word, *value);
}
}