I am creating a program that uses recursion functions to count the vowels in a sentence and to determine if it is a palindrome. The problem I am getting is that it says the sentence entered is not palindrome even if it is.. Any help with this will be greatly appreciated. Thank you.
#include<iostream>
#include <cmath>
using namespace std;
struct Sentence
{
int CountVowels(string , int);
public:
Sentence (string);
bool isPal(string , int);
void Print();
string s;
int numVowel;
int length;
//~Sentence();
};
Sentence :: Sentence (string b)
{
s = b;
length = 0;
numVowel = CountVowels(s, 0);
}
int Sentence :: CountVowels(string myWord, int startindex)
{
length ++;
int pandi;
if(myWord[startindex])
{
if (myWord[startindex] != 'a' && myWord[startindex] != 'e' && myWord[startindex] != 'i' && myWord[startindex] != 'o' && myWord[startindex] != 'u')
{
pandi = 0;
}
else pandi = 1;
return pandi + CountVowels(myWord, startindex + 1);
}
return 0;
}
bool Sentence :: isPal(string myWord, int size)
{
int r = myWord.size() - size;
int t = size - 1;
if (size == r || r == t)
return true;
if ((myWord[r]) != (myWord[t]))
return false;
return isPal(myWord, -- size);
}
void Sentence :: Print()
{
cout << s [-- length];
if (length == 0)
{
cout << endl;
return;
}
Print ();
}
/*Sentence :: ~Sentence()
{
cout << "\ntilde delete\n\n";
}*/
int main ()
{
string userW;
cout << "Enter a sentence: \n";
getline(cin, userW);
userW.erase(remove_if(userW.begin(), userW.end(), [](char c) {return !isalpha(c); }), userW.end());
Sentence userSent(userW);
cout << "The number of vowels in the sentence is " << userSent.numVowel << endl;
cout << "" << endl;
cout << "The sentence " << userSent.s << " is" <<
(userSent.isPal(userSent.s, userSent.s.size()) ? " Palindrome\n" : " Not Palindrome\n");
return 0;
}
UPDATE:
I am now trying to remove special characters. So it looks like this
string userW;
cout << "Enter a sentence: \n";
getline(cin, userW);
userW.erase(remove_if(userW.begin(), userW.end(), [](char c) {return !isalpha(c); }), userW.end());
But I am getting this error:
In function 'int main()':
88:85: error: 'remove_if' was not declared in this scope
I have reviewed your program. You are trying to out the string in the function pirnt(). Here is the problem ,when you use
cout << "The sentence backwards is: " << userSent.Print();
but funtion Print() does not have any return type.(because this is void type). Here you should use
cout << "The sentence backwards is: " ;
userSent.Print();
and now it works.
Your code is fine except that it does not remove commas, spaces and anything that is not alphabetic from the sentence. Also, you need to do a case-insensitive comparison on the characters. This is required, otherwise the examples
A man, a plan, a canal, Panama
Desserts, I stressed
would not be palidromes.
To remove special characters from the user input, you can use lambda
string userW; cout << "Enter a sentence: \n"; getline(cin, userW);
userW.erase(remove_if(userW.begin(), userW.end(), [](char c) {return !isalpha(c); }), userW.end());
EDIT you can also try the following to avoid the need for lambda:
userW.erase(std::copy_if(userW.begin(), userW.end(), userW.begin(), isalpha), userW.end());
to do a case-insensitive comparison, in the function isPal, you can change this:
if ((myWord[r]) != (myWord[t]))
into this:
if (tolower(myWord[r]) != tolower(myWord[t]))
Related
int countChars(string str)
{
int count = 0;
if (str == "")
return count;
else
{
count++;// add a character to the count
return count + countChars(str.substr(1));// function calls itself
}
}
I need to take the above function and call in in the program below and I'm not sure how to initialize it properly. Below is what I tried and it doesn't work. I'm not allowed to use the .length() because otherwise the program would be done.
int main()
{
char find = '\0';
string str;
int count = 0;
int length = int(countChars);
//ask the user for a sentence
cout << "Enter a sentence " << endl;
getline(cin, str);
//ask the user which letter they want the count of
cout << "Which letter would you like to find the number of appearances: " << endl;
cin >> find;
for (int i = 0; i < length; i++)
{
if (str[i] == find)
{
count++;
}
}
cout << "the letter " << find << " appears " << length << " times " << endl;
//waits for user to exit
system("pause");
cin.get();
}
It seems the function should count the number of appearances of a letter in a string. If so then it is declared and defined incorrectly. It has to have at least two parameters an object of type std::string and an object of type char.
Here is shown how such a recursive function can look
#include <iostream>
#include <string>
size_t countChars( const std::string &s, char c )
{
return s.empty() ? 0 : ( s[0] == c ) + countChars( { s, 1 }, c );
}
int main()
{
std::cout << "Enter a sentence ";
std::string s;
std::getline( std::cin, s );
std::cout << "Which letter would you like to find the number of appearances: ";
char c = '\0';
std::cin >> c;
std::cout << "The letter " << c
<< " appears " << countChars( s, c )
<< " times " << std::endl;
return 0;
}
The program output might look like
Enter a sentence My name is Alycia
Which letter would you like to find the number of appearances: a
The letter a appears 2 times
If you mean a function that just calculates the length of a string then it can look like
size_t countChars( const std::string &s )
{
return s.empty() ? 0 : 1 + countChars( { s, 1 } );
}
and shall be called after the statement
getline(cin, str);
searchingWrite a function conseclets which will receive one string as parameter. The function will determine all cases in which two or more consecutive letters in the string are identical.
For example, if "Barrymoore" is sent to the function, it will say that there are consecutive letters r and o in the string. But if "Bush" is sent to the function, it will say there are no two consecutive letters which are the same.
Here is my code the problem with it is when I put in a letter to find it finds it but not consecutively
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char searching='\0';
string name=" ";
int counter =0;
cout<<"Enter a name : "<<endl;
getline(cin, name);
cout<<"Which letter would you like to count the number of times it appears: "<<endl;
cin>>name;
for(int i=0; i<name.length();i++){
if(sentence[i]==searching){
counter++;
}
}
cout<<"The letter " << searching << " appears "<< counter << " times ";
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main(int argc, char *argv[]) {
char a[30];
int i,c=0;
printf("enter a string\n");
gets(a);
for(i=0;i<strlen(a);i++)
{
if(a[i]==a[i+1])
{
printf("%c is consecutive\n",a[i]);
c++;
}
}
if(c==0)
{
printf("No consecutive letters");
}
return 0;
}
// Check this. This is proper code for your problem.
Here is an implementation making use of the standard algorithm library. I've called "runs" the sequences of identical consecutive letters. The algorithm is not necessarily optimal, but it's simple and that matters too.
void conseclets(std::string const &str) {
// Keep the end of the string, and point i to the first run's beginning
auto e = end(str), i = std::adjacent_find(begin(str), e);
if(i == e)
std::cout << "No repetition.\n";
else do {
// Locate the end of the run (that is, the first different letter)
auto next = std::find_if(i, e, [&i](auto const &c){ return c != *i; });
// Print out the match
std::cout << "Letter " << *i << " is repeated "
<< std::distance(i, next) << " times.\n";
// Skip to the next run's beginning
i = std::adjacent_find(next, e);
// Do so until we reached the end of the string
} while(i != e);
}
Live on Coliru
though there are several ways to do it, just modifying yours optimally to achieve whats required here :
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
char searching = '\0';
string name = " ";
int counter = 0;
cout << "Enter a name : " << endl;
getline(cin, name);
cout << "Which letter would you like to count the number of times it appears: " << endl;
cin >> searching;
for (int i = 0; i < name.length(); i++) {
if (name[i] == searching) {
counter++;
}
}
cout << "The letter " << searching << " appears " << counter << " times ";
return 0;
}
#include <iostream>
#include <iterator>
using namespace std;
template<typename I, typename O> O repeats(I b, I e, O result){
while(b!=e){
bool once = true;
I p = b;
while(++b!=e && *p==*b){
if(once){
*result++ = *p;
once = false;
}
}
}
return result;
}
int main() {
string name = "Barrymoore";
string res;
repeats(begin(name), end(name), back_inserter(res));
cout << "There are " << res.size() << " consecutive letters :" << res << endl;
return 0;
}
I'm writing a source and header file that are implemented by a program with some other files, and I need to make the code work by only editing the one source/header files (game.h and game.cpp). I'm trying to call another function from another source/header file, but it's not working right. Here's my code
game.cpp
#include "game.h"
#include "guesser.h"
#include "provider.h"
using namespace std;
const char FILL_CHARACTER = '.';
string wordSoFar;
int numMissedGuesses;
const int MAX_MISTAKE_LIMIT = 10;
void Game::setUpGame (int wordLength)
{
wordSoFar = string(wordLength, FILL_CHARACTER);
numMissedGuesses = 0;
}
bool Game::guesserHasWon()
{
return wordSoFar.find(FILL_CHARACTER) == string::npos;
}
bool Game::guesserHasLost()
{
return numMissedGuesses >= MAX_MISTAKE_LIMIT;
}
void Game::guessHasBeenMade (char guess)
{
bool isInWord;
Provider::getResponseToGuess(guess, isInWord, wordSoFar);
if (isInWord)
{
characterIsInWord (guess, wordSoFar);
}
else
{
++numMissedGuesses;
characterIsNotInWord (guess);
}
}
game.h
#ifndef GAME_H
#define GAME_H
#include <string>
class Provider;
class Guesser;
class Game{
const char FILL_CHARACTER;
std::string wordSoFar;
int numMissedGuesses;
const int MAX_MISTAKE_LIMIT;
void setUpGame (int wordLength);
bool guesserHasWon();
bool guesserHasLost();
void guessHasBeenMade (char guess);
};
#endif
provider.h
#ifndef PROVIDER_H
#define PROVIDER_H
#include <string>
class Provider {
public:
int initialPrompt ();
void getResponseToGuess (char guess, bool& isInWord,
std::string& wordSoFar,
int numMissedGuesses);
std::string providerHasWon ();
void providerHasLost (std::string wordSoFar);
private:
};
#endif
provider.cpp
#include "provider.h"
#include "game.h"
#include <iostream>
using namespace std;
int Provider::initialPrompt ()
{
cout << "Let's play Hangman!\n\n"
<< "Please think of a word from 4-9 characters long. The word\n"
<< "should not be a proper name (something that you would normally\n"
<< "capitalize, nor should it contain any punctuation characters.\n"
<< "\n\nOK, got a word?\n" << endl;
int len = 1;
while (len < 4 || len > 9)
{
cout << "How long is your word? " << flush;
cin >> len;
if (len < 4 || len > 9)
{
cout << "Please choose a word between 4 and 9 characters long."
<< endl;
}
}
return len;
}
bool getYesNoResponse()
{
string response;
getline (cin, response);
while (response.size() == 0 ||
(response[0] != 'y' && response[0] != 'Y'
&& response[0] != 'n' && response[0] != 'N'))
{
if (response.size() > 0)
cout << "Please respond 'yes' or 'no'. " << flush;
getline (cin, response);
}
return response[0] == 'y' || response[0] == 'Y';
}
void Provider::getResponseToGuess (char guess, bool& isInWord,
std::string& wordSoFar,
int numMissedGuesses)
{
cout << "I have missed " << numMissedGuesses << " guesses ("
<< Game::MAX_MISTAKE_LIMIT - numMissedGuesses << " misses left)"
<< endl;
cout << "\n" << wordSoFar << "\n";
for (int i = 1; i <= wordSoFar.size(); ++i)
cout << i;
cout << "\n\nDoes your word contain the letter '"
<< guess << "'? (y/n) " << flush;
isInWord = getYesNoResponse();
if (isInWord) {
string response;
bool done = false;
string newWord;
while (!done)
{
cout << "Enter all of the character positions (1-"
<< wordSoFar.size() << ") in which the letter '"
<< guess << "' appears: " << flush;
getline (cin, response);
bool digitsFound = false;
newWord = wordSoFar;
for (int i = 0; i < response.size(); ++i)
{
char d = response[i];
if (d >= '1' && d <= '0' + wordSoFar.size())
{
int k = d - '1';
if (wordSoFar[k] == Game::FILL_CHARACTER)
{
newWord[k] = guess;
digitsFound = true;
}
}
}
if (digitsFound)
{
cout << "Like this: " << newWord << "? (y/n) " << flush;
bool yn = getYesNoResponse();
if (yn)
{
wordSoFar = newWord;
done = true;
}
}
}
}
}
/**
* Announce that the provider has won the game, and get the
* provider's actual word.
*/
std::string Provider::providerHasWon ()
{
cout << "Congratulations, you have won." << endl;
cout << "\nOut of curiosity, what was your word? " << flush;
string answer;
getline (cin, answer);
return answer;
}
/**
* Announce that the guesser has won the game, and get the
* provider's actual word.
*/
void Provider::providerHasLost (string wordSoFar)
{
cout << wordSoFar
<< "\n\nI have won!\nThanks for playing" << endl;
}
My problem is the line
Provider::getResponseToGuess(guess, isInWord, wordSoFar);
It was originally just
getResponseToGuess(guess, isInWord, wordSoFar);
but I've tried several variations. I've tried Provider::Provider and Provider.getReponseToGuess, and a bunch of others, but nothing seems to work. Can anyone help me with this? I'm just trying to call the function from the provider files.
EDIT: I have the same problem calling a function from the guesser files, I tried doing it the same way I did with provider, but it gives me the error "no matching function for call to Guesser::Guesser();
Provider providerobj;
Guesser guesserobj;
providerobj.getResponseToGuess(guess, isInWord, wordSoFar, numMissedGuesses);
if (isInWord)
{
guesserobj.characterIsInWord(guess, wordSoFar);
}
I tried doing it the same way as I did with providerobj, but it won't work for some reason.
Here's the code for guesser.
guesser.cpp
#include "guesser.h"
#include "game.h"
#include <iostream>
#include <fstream>
using namespace std;
const std::string Guesser::alphabet = "abcdefghijklmnopqrstuvwxyz";
// Initialize the guesser for a game wit hthe indicated wordlength,
// using words from an indicated file.
Guesser::Guesser (int wordLength, const char* wordListFilename)
{
for (int i = 0; i < 26; ++i)
charactersTried[i] = false;
string word;
ifstream in (wordListFilename);
while (in >> word)
{
if (word.size() == wordLength)
{
// word is of desired length
if (word.find_first_not_of(alphabet) == string::npos) {
// word contains only lowercse alphabetics
possibleSolutions.push_back (word);
}
}
}
in.close();
}
/**
* Scan the words that are possible solutions so far, counting, for
* each letter not already tried, the number of words with that letter.
* Guess the letter that occurs in the most words.
*/
char Guesser::guessACharacter()
{
int counts[26];
for (int i = 0; i < 26; ++i)
counts[i] = 0;
// Count the number of words in which each letter can be found
for (int i = 0; i < possibleSolutions.size(); ++i)
{
string word = possibleSolutions[i];
for (char c = 'a'; c <= 'z'; ++c)
{
if (!charactersTried[c- 'a'])
{
// Character c has not been tried yet
if (word.find(c) != string::npos)
// c is in this word
++counts[c - 'a'];
}
}
}
// Find the character that occurs in the most words
char guess = ' ';
int maxSoFar = -1;
for (char c = 'a'; c <= 'z'; ++c)
{
if (counts[c - 'a'] > maxSoFar)
{
guess = c;
maxSoFar = counts[c - 'a'];
}
}
if (maxSoFar <= 0)
{
guess = 'a';
while (charactersTried[guess-'a'])
++guess;
}
charactersTried[guess-'a'] = true;
return guess;
}
/**
* Following a successful guess of a letter in the word, make a pass through
* the possibleSolutions, removing all words that do not contain the
* guess character in the positions indicated in wordSoFar.
*/
void Guesser::characterIsInWord (char guess, const string& wordSoFar)
{
vector<string> remainingSolutions;
for (int i = 0; i < possibleSolutions.size(); ++i)
{
string wd = possibleSolutions[i];
bool OK = true;
for (int k = 0; OK && k < wordSoFar.size(); ++k)
{
if (wordSoFar[k] == guess)
{
if (wd[k] != guess)
{
OK = false;
}
}
}
if (OK)
{
//cerr << "Keeping " << wd << endl;
remainingSolutions.push_back (wd);
}
}
possibleSolutions = remainingSolutions;
}
/**
* Following a mistaken guess of a letter in the word, make a pass through
* the possibleSolutions, removing all words that contain the
* guess character.
*/
void Guesser::characterIsNotInWord (char guess)
{
vector<string> remainingSolutions;
for (int i = 0; i < possibleSolutions.size(); ++i)
{
string wd = possibleSolutions[i];
if (wd.find(guess) == string::npos)
{
remainingSolutions.push_back (wd);
}
}
possibleSolutions = remainingSolutions;
}
/**
* Guesser has lost the game. Look at the provider's actual word
* and gripe a bit about losing.
*/
void Guesser::admitToLoss (std::string actualWord, const string& wordSoFar)
{
bool match = actualWord.size() == wordSoFar.size();
for (int i = 0; match && i < actualWord.size(); ++i)
{
match = wordSoFar[i] == Game::FILL_CHARACTER ||
wordSoFar[i] == actualWord[i];
}
if (!match)
{
cout << "Ummm...your word '" << actualWord
<< "' does not match the patterh '"
<< wordSoFar <<"'.\nDid you make a mistake somewhere?"
<< endl;
}
else
{
for (int i = 0; match && i < actualWord.size(); ++i)
{
if (wordSoFar[i] == Game::FILL_CHARACTER
&& charactersTried[actualWord[i]-'a'])
{
cout << "Did you forget to mention the '"
<< actualWord[i]
<< "' in position " << i+1 << "?"
<< endl;
return;
}
}
for (int i = 0; (!match) && i < possibleSolutions.size(); ++i)
match = (actualWord == possibleSolutions[i]);
match = match && (possibleSolutions.size() > 0);
if (match)
{
cout << "OK, I might have guessed that eventually." << endl;
}
else
{
cout << "Interesting, I don't know that word. Are you sure you\n"
<< "spelled it correctly?." << endl;
}
}
}
guesser.h
#ifndef GUESSER_H
#define GUESSER_H
#include <string>
#include <vector>
class Game;
class Guesser {
public:
// Initialize the guesser for a game with the indicated wordlength,
// using words from an indicated file.
Guesser (int wordLength, const char* wordListFilename);
/**
* Scan the words that are possible solutions so far, counting, for
* each letter not already tried, the number of words with that letter.
* Guess the letter that occurs in the most words.
*/
char guessACharacter();
/**
* Following a successful guess of a letter in the word, make a pass through
* the possibleSolutions, removing all words that do not contain the
* guess character in the positions indicated in wordSoFar.
*/
void characterIsInWord (char guess, const std::string& wordSoFar);
/**
* Following a mistaken guess of a letter in the word, make a pass through
* the possibleSolutions, removing all words that contain the
* guess character.
*/
void characterIsNotInWord (char guess);
/**
* Guesser has lost the game. Look at the provider's actual word
* and gripe a bit about losing.
*/
void admitToLoss (std::string actualWord, const std::string& wordSoFar);
private:
// A collection of words that match all guesses made so far
std::vector<std::string> possibleSolutions;
// Tracks characters already guessed.
// charactersTried[c-'a'] is true if the character c
// has been guessed previously
bool charactersTried[26];
static const std::string alphabet;
};
#endif
Provider::getResponseToGuess(guess, isInWord, wordSoFar); will not work because, getResponseToGuess is not a static function.
Provider.getReponseToGuess also wrong because Provider is a class, not an object, you can't call a member function of a class with class name.
you have to create a object of the class first, then call the member function with the object.
Provider provider_obj;
proveder_obj.getResponseToGuess(guess, isInWord, wordSoFar);
if you are new to C++, I would suggest first try some basic programs.
So I'm working on this homework assignment and I'm really having trouble. I'm supposed to count the number of words more than two characters(have to contain one letter), unique words, and the number of times each unique word appears in the Programming Execution Environment. I'm also supposed to get input to search for in the PEE and output the number of times it appears and the line where it appears. I have some of it working, but I'm really struggling with counting how many times each word appears. I know my code is really bad right now, but that's why I'm here. I'm really struggling with these string functions for some reason. Any help is really appreciated!
#include <iostream>
#include <cstring>
#include <string>
#include <cctype>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
//PEE string
string envstr("");
bool checkChar(unsigned c)
{
return (ispunct(c) || isspace(c) || isblank(c) || isdigit(c) || c == '\n');
}
void searchWord(unsigned c, size_t length)
{
multiset<string> words;
vector<string> vwrds; //this was something i was trying out
string tempword;
while (!checkChar(envstr[c]) && c < length)
{
tempword = tempword + envstr[c]; //problem here
c++;
}
tempword = tempword + " ";
vwrds.push_back(tempword);
words.insert(tempword); //this is just a bunch of random letters
tempword.clear();
//for (multiset<string>::const_iterator i(words.begin()), end(words.end()); i != end; i++)
//cout << *i;
}
bool checkIfWord(char c)
{
bool valid = false;
int i;
for (i = c; i > c - 2; i--)
{
if (!checkChar(envstr[i]))
valid = true;
}
if (valid)
searchWord(i, envstr.length());
return valid;
}
int main()
{
//this code given by my instructor
extern char **environ; // needed to access your execution environment
int k = 0;
size_t wordCount = 0;
while (environ[k] != NULL)
{
cout << environ[k] << endl;
string str(environ[k]);
envstr = envstr + str;
k++;
}
//iterator to count words
wordCount = count_if(envstr.begin(), envstr.end(), checkIfWord);
cout << "\nThe PEE contains " << wordCount << " words. \n";
//transform environment string to lowercase
transform(envstr.begin(), envstr.end(), envstr.begin(), tolower);
string input;
do
{
cout << "Enter your search item: \n";
cin >> input;
//string can only be forty characters
if (input.length() > 40 || input == "\n")
{
cout << "That search query is too long. \n";
continue;
}
//change the search string to lowercase, like the envstr
transform(input.begin(), input.end(), input.begin(), tolower);
int j = 0;
int searchCount = 0;
vector<size_t> positions;
size_t pos = envstr.find(input, 0);
//search for that string
while (pos != string::npos)
{
positions.push_back(pos);
pos = envstr.find(input, pos + 1);
searchCount++;
}
cout << "\nThat phrase occurs a total of " << searchCount << " times.\n";
cout << "It occurs in the following lines: \n";
//output where that string occurs
for (vector<size_t>::iterator it = positions.begin(); it != positions.end(); ++it)
{
for (int i = *it; i < envstr.length() - 1 && checkChar(envstr[i]); i++)
{
cout << envstr[i];
}
cout << endl;
}
positions.clear();
} while (input != "END");
cin.get();
return 0;
}
First, your function checkChar() returns false when the parameter is a char, so if you want to print where that string occurs, it should be:
for (int i = *it; (i < envstr.length() - 1) && !checkChar(envstr[i]); i++)
{
cout << envstr[i];
}
Second, the code for counting words makes no sense and there is a potential out-of-bounds here: if (!checkChar(envstr[i])), I would suggest you to split the string using delimter '\', then do something.
My program prompts a user for a phrase to check if its a palindrome, then it's supposed to print out the phrase without capitalization or special characters like " ' , ? etc. My problem is erasing those characters. I've gotten my program to ignore them I'm asking how should I erase them? I made a comment where I think the statement should go. Example output should be: "Madam I'm Adam" to "madamimadam"
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
//Variables and arrays
int const index = 80;
char Phrase[index];
char NewPhrase[index];
int i, j, k, l;
bool test = true;
//Prompt user for the phrase/word
cout << "Please enter a sentence to be tested as a palindrome: ";
cin.getline(Phrase, 80);
//Make everything lowercase, delete spaces, and copy that to a new array 'NewPhrase'
for(k = 0, l = 0; k <= strlen(Phrase); k++)
{
if(Phrase[k] != ' ')
{
NewPhrase[l] = tolower(Phrase[k]);
l++;
}
}
//cout << "The Phrase without punctuation/extra characters: " << newPhrase[l];
int length = strlen(NewPhrase); //Get the length of the phrase
for(i = 0, j = length-1; i < j; i++, j--)
{
if(test) //Test to see if the phrase is a palindrome
{
if(NewPhrase[i] == NewPhrase[j])
{;}
else
{
test = false;
}
}
else
break;
}
if(test)
{
cout << endl << "Phrase/Word is a Palindrome." << endl << endl;
cout << "The Palindrome is: " << NewPhrase << endl << endl;
}
else
cout << endl << "Phrase/Word is not a Palindrome." << endl << endl;
system("Pause");
return 0;
}
Modify this line:
if(Phrase[k] != ' ')
To be:
if((phrase[k] != ' ') && (ispunct(phrase[k]) == false))
This means that we check for spaces and punctuation at the same time.
Also, consider rewriting this:
if(NewPhrase[i] == NewPhrase[j])
{;}
else
{
test = false;
}
As this:
if(NewPhrase[i] != NewPhrase[j])
test = false;
Here's suggestion:
Use an std::string
Use std::ispunct to determine whether a character in the string is a punctuation mark
Use the erase-remove idiom to remove punctuation
That is one line of code (plus one extra line for a convenience lambda):
std::string phrase = .....;
auto isPunct = [](char c) { return std::ispunct(static_cast<unsigned char>(c)); }
phrase.erase(std::remove_if(phrase.begin(), phrase.end(), isPunct),
phrase.end());
Next, for turning into lower case, from my answer to this recent question, another one-liner:
std::transform(phrase.begin(), phrase.end(), phrase.begin(),
[](char c)
{ return std::tolower(static_cast<unsigned char>(c));});