So I've written a program to check whether a sentence is a palindrome or not. I specifically used an array for that and the program is supposed to ignore spaces (and possibly the difference between normal and capital letters). I could only find on the web how to achieve this using strings.
Is it possible with arrays? I tried using delete[] etc. and it refuses to work properly.
#include <iostream>
#include <cctype> // std::isspace, std::tolower
int main()
{
start_of_main:
char willcontrol[200];
std::cout<<"Enter a phrase: ";
std::cin.getline( willcontrol, sizeof(willcontrol) );
// determine the number of characters entered by the user
// http://en.cppreference.com/w/cpp/io/basic_istream/gcountconst std::size_t nchars = std::cin.gcount() - 1 ;
if( nchars == 0 ) goto start_of_main ; // empty input; repeat
bool ensign = true ;
std::size_t left = 0 ; // initially beginning of string
std::size_t right = nchars-1 ; // initially last character in string
while( left < right && ensign )
{
// skip to next character if white space in encountered
if( std::isspace( willcontrol[left] ) ) ++left ;
elseif( std::isspace( willcontrol[right] ) ) --right ;
// compare the character at the left with that at the right ignoring case
elseif( std::tolower( willcontrol[left] ) == std::tolower( willcontrol[right] ) )
{
// palidrome so far, get to the next pair if characters
++left ;
--right ;
}
else ensign = false ; // not a palindrome
}
if(ensign) std::cout << "It is a palindrome.\n" ;
else
{
std::cout << "It is not a palindrome.\n" ;
goto start_of_main ;
}
}
With std::istream::getline(), the terminating null character is counted as an extracted character.
The count returned by gcount() includes the terminating null character;
and gcount()-1 gives us the length of the extracted c-style string.
If the string has N characters ( gcount()-1 == N ), the position of the last character would be N-1.