Home > Back-end >  Code that checks if a words from string is a palindrome. Can't recognize words at the end of th
Code that checks if a words from string is a palindrome. Can't recognize words at the end of th

Time:01-30

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define NMAX 1000

int main()
{
    char line[NMAX];
    int palindromo = 1;

    FILE*fp;

    fp=fopen("input.txt", "r");
    if(fp != NULL){
        while(fgets(line, NMAX, fp)){

            char*word = strtok(line, " ");
            while(word != NULL){

                palindromo = 1;

                int lunghezza = strlen(word);

                if((lunghezza>0) && (word[lunghezza-1] == '\n')){
                    word[lunghezza-1] = '\0';
                }


                for(int i=0; i<lunghezza; i  ){
                    word[i] = tolower(word[i]);
                }


                for(int i=0; i<lunghezza/2; i  ){
                    if(word[i] != word[lunghezza-1-i]){
                        palindromo = 0;
                    }

                }

                if(palindromo == 1){
                    for(int i=0; i<lunghezza; i  ){
                        word[i] = toupper(word[i]);
                    }
                }

                puts(word);

                word = strtok(NULL, " ");
            }

        }
    }
}

the input file is this:

Anna ha preso otto a scuola. la mamma le ha regalato una spilla in oro e le ha organizzato un giro in kayak
Anche il cane ha avuto in premio un osso lo ha mangiato come un ossesso.

The only words that the program is not recognizing as palindrome are kayak and ossesso (both at the end of the strings).

Sry the code and the input.txt file are in italian.

CodePudding user response:

When word[lunghezza-1] == '\n', you replace the \n with \0. You also need to reduce lunghezza by 1.

                if((lunghezza>0) && (word[lunghezza-1] == '\n')){
                    word[lunghezza-1] = '\0';
                    --lunghezza;
                }

CodePudding user response:

As already noted by @RobMayoff, you must account for shortening the length of the last word in the buffer.

You could save yourself grief and code by using " \n" as the delimiter in both calls to strtok(). The function would clobber both the SP and newline characters delivering back pointers to individual words.

word = strtok( line, " \n" );

In so doing, you eliminate some of your code (that happened to have a bug.)


To avoid the opportunity of a future bug by having two separate invocations of strtok(), the operation could be rewritten in one line:

for( char *word = line; (word = strtok( word, " \n" ) ) != NULL; word = NULL )

Think your way through this for() loop and see why it works.

Less code (that works) is better.

  •  Tags:  
  • c
  • Related