2
I’m trying to make a program to check if a certain word is a palindrome. I’m having trouble with a logical operation that isn’t returning what I expected.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define bool short
#define true 1
#define false 0
#define equals(a, b) (((strcmp(a, b) == 0 ) ? true : false))
#define NUMENTRADA 1000
#define TAMLINHA 1000
bool isFim (char* s){
return (strlen(s) >= 3 && s[0] == 'F' && s[1] == 'I' && s[2] == 'M');
}
bool isPalindromo(char* s){
int meio = strlen(s)/2;
int indc = strlen(s) - 1;
bool resp = true;
// printf("\nresp ==>> %d \n", resp);
for (int i = 0 ; i < meio ; i++){
// printf("\nresp2 ==>> %d \n", resp);
// printf("BOOL2 ======= >> %d \n", (resp && (s[i] == s[indc])));
resp = resp && (s[i] == s[indc]);
indc--;
// printf("VALOR ======= >> %c \n", s[i]);
// printf("VALOR 2 ======= >> %c \n", s[indc]);
// printf("\nRESP ======= >> %d \n", resp);
// printf("BOOL ======= >> %d \n", (resp && (s[i] == s[indc])));
}
// printf("\n---------------------------\n");
// printf("BOOL ======= >> %d \n", (s[i] == s[indc]));
// printf("\n---------------------------\n");
return resp;
}
int main (int argc, char** argv){
char entrada [NUMENTRADA][TAMLINHA];
int numEntrada = 0;
do{
fgets(entrada[numEntrada], TAMLINHA, stdin);
} while (isFim(entrada[numEntrada++]) == false);
numEntrada--;
for (int i = 0; i < numEntrada ; i++){
if(isPalindromo(entrada[i]) == true){
printf("SIM\n");
} else {
printf("NAO\n");
}
}
}
Good operation:
resp = resp && (s[i] == s[indc]);
is always returning me false (0) and did not understand why.
The words are being entered into the program by incoming redirect. Here is a part of the.in input file:
aça
acaçá
Ada
afã
aia
ala
ama
Ana
anilina
ara
arara
asa
ata
aviva
ele
esse
mamam
mamam
matam
metem
oco
omissíssimo
Omo
osso
Oto
Otto
ovo
racificar
I made a similar code in Java and managed, but I’m not able to understand why the comparison is not working.
One thing I noticed in your entries is that you have uppercase/lowercase words and in this case the comparison will be different, which I do not know if it is something purposeful or not. Ex.: Omo. Idem for accented letters. The problem with your program is that the fgets function incorporates the final input ' n' to your string, so your ara input will have length 4 and will be: s[0]='a', s[1]='r', s[2]='a' and s[3]=' n'.
– anonimo