Hi everybody. I want to use fgets to read a line of text and a word. The text is examined to find the word, but the word is never found even when the word is in the text. What am I doing wrong? Thanks. Code: #define TEXT_LEN 100 #define WORD_LEN 20 char text[TEXT_LEN]; char word[WORD_LEN]; printf("Enter the text to be searched:\n"); fgets(text, TEXT_LEN, stdin); printf("Enter the word sought:\n"); fgets(word, WORD_LEN, stdin); if(strstr(text, word)) puts("The word sought was found"); else puts("The word sought was not found");
The problem is the character '\n' at the final of the word. fgets reads the new line character. Use gets(word) instead of fgets(word, WORD_LEN, stdin).
Urm... no. gets will betray you as it offers no boundary check. There's nothing preventing a user from trying to stuff 100,000 characters into your 20 character array, and trash memory elsewhere. Code: char text[TEXT_LEN] = { 0 }, *p; fgets(text, sizeof text, stdin); if((p = strchr(text, '\n')) != NULL) *p = 0; else while(getchar() != '\n') {}
It's because fgets stores the newline character so when strstr does a comparison it fails. From the main page: fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer. Innovative Web Apps here: ati-erp.com