i have relatively simple bit of c code - takes in file dict.txt of words (one word per line, alphabetic letters , lower case).
the goal "load" each word array called word, print word, , repeat until eof.
currently, printf("%s\n", ptr)
prints blank line console, rather string - intended. why , how can fix?
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include "dictionary.h" int main(void) { // open given dictionary file* dict; dict = fopen("dict.txt", "r"); char word[46]; int index = 0; // navigate word array char *ptr = word; // start loading words (int c = fgetc(dict); c != eof; c = fgetc(dict)) { // allow alphabetical characters , apostrophes if (isalpha(c) || (c == '\'' && index > 0)) { // append character word word[index] = c-97; index++; } // must have found whole word else if (index > 0) { // terminate current word word[index] = '\0'; printf("%s\n", ptr); // prepare next word index = 0; } } // check whether there error if (ferror(dict)) { fclose(dict); printf("error reading.\n"); return 1; } // close text fclose(dict); return 0; }
edit: moved ferror()
call after loop avoid null error.
you meant,
word[index] = c;
you don't need perform calculations, specially because isalpha()
ensures c
ascii character.
and fix this
- if
fopen()
fails returnsnull
pointer,ferror()
callednull
pointer parameter , undefined behavior, instead checkdict != null
.
Comments
Post a Comment