Here is the code

#include <stdlib.h> #include <string.h> #include <stdio.h> int main () { char str[80]; int i,j,temp; const char s[2] = " "; char *token; char *token2; fgets(str,sizeof(str),stdin); token = strtok(str, s); token2=token; printf("\n%s",token2); while( token != NULL ) { i=0; j=strlen(token)-1; while(i<j){ temp=token[i]; token[i]=token[j]; token[j]=temp; i++; j--; } printf("\n%s",token2); token = strtok(NULL, s); } return 0; } 

His task, to display all palindromes found in the phrase. But the program does not correctly respond to this insert:

 token2=token; 

If I enter for example the word: the book It displays:

 книга агинк 

Although token2 did not change in the while loop, why is this happening?

  • one
    token and token2 - pointers, and after 'token2 = token;' point to the same memory. And you change token [i]. - Drawn Raccoon
  • And how can this be fixed? - Ax1
  • I don’t really understand why you need token2 and why you invert the token, to search for a palindrome it is enough to check that token [i] == token [j]; if not satisfied, then this is not a palindrome - Drawn Raccoon
  • I will need token2 to check two words with strcmp (), one vice versa and one original, I want to use token2 as the original, and token the word after inverting. Palindrome is when the word written on the contrary goes the same word. For example: Madame, Ana, and so on. - Ax1

1 answer 1

 #include <ctype.h> #include <stdlib.h> #include <string.h> #include <stdio.h> int main() { char str[80]; int i, j, temp; const char s[] = " \n"; char *token; fgets(str, sizeof(str), stdin); token = strtok(str, s); while (token != NULL) { i = 0; j = strlen(token) - 1; bool palindrome = true; while (i < j) { if (tolower(token[i]) != tolower(token[j])) { palindrome = false; break; } i++; j--; } if (palindrome) { printf("\n%s", token); } token = strtok(NULL, s); } return 0; } 
  • After the last edit, everything works as it should, thanks, I understand the error. - Ax1