2016-03-07 2 views
0

Я пытаюсь создать программу, которая принимает входные данные из файла, помещает каждое слово в структуру «слов», а затем выводит результаты с частотой каждого слова, но всякий раз, когда я пытаюсь вывести строку, она просто печатает что-то вроде? k @ ?? где я ожидал бы, что строка будет.Вывод строки из структуры

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct s_words { 
     char *str; //stores the word; no pre-determined size 
     int count; 
     struct s_words* next; 
} words; 

words* create_words(char* word) { 
     //allocate space for the structure 
     words* newWord = malloc(strlen(word)); 
     if (NULL != newWord){ 
      //allocate space for storing the new word in "str" 
      //if str was array of fixed size, storage wud be wasted 
      newWord->str = (char *)malloc(strlen(word)); 
      strcpy(newWord->str,word); //copy “word” into newWord->str 
      newWord->str[strlen(word)]='\0'; 
      newWord->count = 1; //initialize count to 1; 
      newWord->next = NULL; //initialize next;    
     } 
     return newWord; 
} 

//If the word is in the list, add 1 to count. 
words* add_word(words* wordList, char* word) { 
     int found=0; 
     words *temp=wordList; 
     // search if word exists in the list; if so, make found=1 
     while (temp!=NULL) { 
     // printf("looptest\n"); 
     if (strcmp(word,temp->str) == 0) { //use strcmp command 
      //printf("looptest0\n"); 
      found=1; 
      temp->count = temp->count + 1; //increment count; 
      return wordList; 
      //printf("looptest1\n"); 
     } 
     else { 
      temp = temp -> next; //update temp 
      // printf("looptest2\n"); 
     } 
     } 
    // printf("looptest3\n"); 
     //new word 
     words* newWord = create_words(word); 
     // printf("looptest4\n"); 
      if (NULL != newWord) { 
       // printf("looptest5\n"); 
       newWord->next = wordList; 
       wordList = newWord; 
       //Insert new word at the head of the list 
      } 
      else{ 
       // printf("looptest6\n"); 
       temp = wordList; 
       while(temp->next != NULL){ 
        // printf("looptest7\n"); 
        temp = temp->next; 
       } 
       temp->next = newWord; 
      } 
      return newWord; 
} 


int main(int argc, char* argv[]) { 

    words *mywords; //head of linked list containing words 
     mywords=NULL; 

    FILE *myFile; 
    myFile = fopen(argv[1],"r"); //first parameter is input file 
     if (myFile==0) { 
     printf("file not opened\n"); 
     return 1; 
    } 
    else { 
     printf("file opened\n"); 
    } 

    //start reading file character by character; 
    //when word has been detected; call the add_word function 
    int ch, word = 0, k=0; 
    char thisword[100]; 

     while ((ch = fgetc(myFile)) != EOF) 
     { 
      // printf("%c",ch); 
     if (ch==' ' || ch==',' || ch==';' || ch==':' || ch == '.') //detect new word? Check if ch is a delimiter 
     { 
      // printf("\ncheck2\n"); 
      if (word) //make sure previous character was not delimiter 
      { 
       // printf("check\n"); 
       word = 0; 
       thisword[k] = '\0'; //make the kth character of thisword as \0 
       // printf("test2\n"); 
       //now call add_word to add thisword into the list 
       mywords = add_word(mywords,thisword); 
       // printf("check3\n"); 
       k=0; 
      } 
      // printf("test\n"); 
     } 
     else 
     { 
      word = 1; 
      thisword[k] = ch; //make the kth character of thisword equal to ch 
     k++; 
     } 
     if(ch == EOF){ 
      thisword[k] = '\0'; 
      mywords = add_word(mywords,thisword); 
     } 
     } 

    printf("%s\n",mywords->str); 
    printf("printing list\n"); 

    //Traverse list and print each word and its count to outputfile 
    //output file is second parameter being passed 
    //haven't started to deal with the output file 
    words* temp = mywords; 
    while(temp != NULL){ 
     printf("%s\tcount: %i\n",temp->str,temp->count); 
     temp = temp->next; 
    } 
    printf("list complete\n"); 
    return 0; 
} 

Это все мой код, я не могу понять, как ошибки теста, в чем проблема, так как я не могу понять, как вывести строки. Я только начал программировать в C в этом году, поэтому я предполагаю, что есть что-то основное, что мне не хватает.

+1

Не удалось выделить место для нулевого терминатора. –

+0

@MartinJames Что это значит? Я добавил 1 в команду malloc в create_words, но это ничего не меняло – rdennis42

+0

Надеюсь, ради вас, что ни слова не короче 'sizeof (words)', иначе вы выделите небольшую память для структуры в 'create_words '. –

ответ

0
newWord->str = (char *)malloc(strlen(word)); 
    strcpy(newWord->str,word); //copy “word” into newWord->str 
    newWord->str[strlen(word)]='\0'; 

.. записывает нулевую отметку.

Предполагая, что STRLEN() возвращает требуемое значение, вы должны таНос дополнительный символ:

newWord->str = (char *)malloc(1+strlen(word)); 

Примечание Olaf комментарий повторно. литье в C. Также обратите внимание, что маловероятно, что это ваша ТОЛЬКО ошибка.

+0

Не бросайте 'void *' – Olaf

+1

@ Олаф, спасибо, что указал на мои чрезмерно хорошие навыки копирования/вставки :) –

+0

Пытался добавить это, ничего не менял – rdennis42

Смежные вопросы