c++ program to find palindrome number code example

Example 1: palindrome c++

#include<iostream>
#include<string>
#include<algorithm>
bool IsPalindrome_true_false(const std::string& );
int main ()
{
    
    std::cout<<"Please enter a string:\t";
    std::string str;
    getline(std::cin, str);
    
    // convert the string from uppercase to lowercase 
    int i = 0;
    while(str[i])
    {
        if(str[i] == std::toupper(str[i]) && std::isalpha(str[i]) == 1024)
        str[i]+= 32;
        ++i;
    }
    // looping while string is empty 
    while(str.empty())
    {
        std::cout<<"\nPlease enter a string your string is empty:\t";
        if(!str.empty())
        std::string str;
        getline(std::cin, str);
    }
    
    std::cout<<"\n"<<std::boolalpha<<IsPalindrome_true_false(str)<<std::endl;
    std::cout<<std::endl;

    return 0;
}

// check if string is a palindrome and return true or false 
bool IsPalindrome_true_false(const std::string& str)
{

    int i = 0;                
    int j = str.length() - 1; 

    while(i <= j )
    {   
        
        if(std::isalpha(str[i]) == 0){
            ++i;
            continue;
        }else if(std::isalpha(str[j]) == 0){
            --j;
            continue;
        }   
        if(str[i] != str[j]){
        
           return false;
        }
        ++i;
        --j;
    }  
    return true;
}

Example 2: next palindrome number in cpp

#include <iostream>
#include <string.h>
using namespace std;
int nextpalin (int num){
    while (num++) {
        string str = to_string (num); /// int to string conversion
        int l = str.length()-1;
        int s = 0;
        while( s<l ){
              if (str[s]!=str[l]) break;
              else {
                    s++;
                    l--;
                    }
        if (s>=l) return num;}
                }
   }

int main () {
    int t;
    cin >> t;
    while (t--){
    int num;
    cin >> num;
    if (num==0)  cout << "1" << endl;
   else { 
       if (num<9)  cout << num+1 << endl;
       else  cout << nextpalin( num) << endl;}
     }
}

Tags:

Cpp Example