C - program checks only the first word in file

1.1k Views Asked by At

C beginner here. Any suggestions? I have a file containing text and I have to find all words that can be read the same forwards and backwards (palindromes) for example rotator, eye and so on. The problem is that this program checks only the first word in file. Thanks in advance.

That is my code for now:

#include <stdio.h>
#include <string.h>
int main() {
    char buffer[255];
    char one[255];
    char two[255];
    char *fp;
    fp = fopen("duom.txt", "r");
    fgets(buffer, 255, (FILE*)fp);
    sscanf(buffer, "%s", one);

    strcpy(two, one);
    strrev(two);

    if(strcmp(one, two) == 0)
        printf("%s palindrome\n", one);
    else
        printf("%s not palindrome\n", one);

    return 0;
    }
2

There are 2 best solutions below

0
On

Your code will only run once, you need to put your main analysis inside a while loop.

I'll let you test what to loop and how to check the next word.

2
On

The problem is that you need to process every word in your text, and you process just one. In order to repeat your logic for every word in the text, you need a loop. I will not explain this concept, as I provided a reference for it. Instead, I will show you how to do it:

while (!feof(f)) {                // while there are more characters to be analysed
   fscanf(fp, "%s", one);         // read another word
   strcpy(two, one);              // analyse it
   strrev(two);

   if(strcmp(one, two) == 0)
       printf("%s palindrome\n", one);
   else
       printf("%s not palindrome\n", one);
}

Here you can find a reference for the feof function that I am using. The rest of the code is the same as yours.