Palindrome in C ++

3

The code below works, receives what was typed and stores the same, but does not make the logic to show if it is palindrome or not and does not display the result for the user.

Please, where did I go wrong and how to fix it?

#include <iostream>
using namespace std;

int main(void)
{

    string Texto = "";
    bool palindrono = true;
    int posicaoReversa = 0;

        cout << "Digite a palavra : " ;
        cin >> Texto;

    for (int i = Texto.length() -1; i > 0; i--)
    {

        posicaoReversa = Texto.length() - i - 1;

        if (Texto.substr(i, 1) != Texto.substr(posicaoReversa, 1))
        {
            palindrono = false;
            break;
        }
    }
}

    
asked by anonymous 09.10.2014 / 21:18

1 answer

5

I just needed to present the result, just added a line at the end of the character check. I commented on some improvements you can make in your code and made them in the example shown in ideone , consider especially halving the algorithm time by avoiding comparing what has already been compared:

#include <iostream>
using namespace std;
int main(void) {
    string Texto = ""; //foi sempre usado camelcase, esta variável também deveria ser
    bool palindrono = true; //o nome da variável deveria ser palindromo
    int posicaoReversa = 0; //variável desnecessária
    cout << "Digite a palavra : ";
    cin >> Texto;
    //seria melhor pegar o tamanho do texto for do loop por questões de performance
    //também seria melhor comparar só até a metade, veja no ideone o exemplo modificado
    for (int i = Texto.length() - 1; i > 0; i--) {
        posicaoReversa = Texto.length() - i - 1; //não precisava colocar na variável
        //poderia usar o operador [] que já pega uma posição da string
        if (Texto.substr(i, 1) != Texto.substr(posicaoReversa, 1)) {
            palindrono = false;
            break;
        }
    }
    //terminou todo o processamento necessário, chegará aqui em duas situações:
    //1. ocorreu o break saindo do for e mandando para cá (não é palindromo)
    //2. terminou o loop do for e não tem mais o que repetir (é palindromo)
    cout << endl << (palindrono ? "É palindromo" : "Não é palindromo");
}

I made some optimizations and code style improvements:

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

When you compare arara , for example, you only need to compare the last with the first and the penultimate with the second. Originally she made three more unnecessary comparisons: she compared the middle one with herself, the second with the penultimate one (which you had already compared) and the first with the last one (I had also compared it). The code was not wrong, it just could be improved.

    
09.10.2014 / 21:31