Saturday 15 May 2010

c - Using fgetc to read words? -



c - Using fgetc to read words? -

i want read text file, character character, , characters , words. implementation:

char c; char* word=""; fp = fopen("text.txt","rt"); { c = (char)fgetc(fp); if(c == ' ' || c == '\n' || c == '\0' || c == '\t') { //wordfunction(word) word = ""; //reset word } else { strcat(word, &c); //keeps track of current word } //characterfunction(c); }while(c != eof); fclose(fp);

however, when seek run programme instantly crashes. there problem setting word ""? if so, should instead?

in word variable initial assignment, you're pointing static string of length 0. when seek write info there, you'll overwrite else , programme brake. need, instead, reserve space words.

where have

char* word="";

use instead

char word[100];

this create space of 100 chars word.

char c; char word[100]; fp = fopen("text.txt","rt"); int index = 0; { c = (char)fgetc(fp); if(c == ' ' || c == '\n' || c == '\0' || c == '\t') { //wordfunction(word) word[0] = 0; //reset word index = 0; } else { word[index++] = c; word[index] = 0; //strcat(word, &c); //keeps track of current word } //characterfunction(c); } while(c != eof); fclose(fp);

c c-strings fgetc

No comments:

Post a Comment