I am trying to skip the spaces in my code using getline();
I think I solved the spacing problem, but I'm trying to make the code check from the beginning of the word and the end of the word at the same time, so that when I type sentences like "ufo tofu" it will come back as a palindrome.
I've tried removing the spaces, but it only causes the system to return me an error.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string userInput;
int startInput;
int endInput;
bool isPalindrome = true;
startInput = userInput.length();
getline (cin, userInput);
cin.ignore();
for (int i = 0; i<(startInput/2); i++){
if (userInput[i] != userInput[(startInput -1) -i])
isPalindrome = false;
}
if (isPalindrome){
cout << userInput << " is a palindrome" << endl;
}
else {
cout << userInput << " is not a palindrome" << endl;
}
return 0;
}
I am trying to make the output come back as "is not a palindrome" when I submit my code to be graded.
These are the two errors that are coming back;
4: Compare output 0 / 2 Output differs. See highlights below. Special character legend Input statistics Your output statistics is a palindrome Expected output statistics is not a palindrome 6: Compare output 0 / 2 Output differs. See highlights below. Special character legend Input evil is alive Your output evil is alive is a palindrome Expected output evil is alive is not a palindrome
string s;
do {
getline(cin, s);
}while(s.empty());
s.erase((remove(s.begin(),s.end(),' ')),s.end());
cout<<s<<endl;
Let's say your string s
is ufo tofu
. It will after erasing all spaces become ufotofu
. That way you can easily check if it's palindrome or not.
How does this thing work ?
s
. In that string, we will store our ufo tofu
input. getline(cin, s);
, but if you pressed enter-key once, it would stop your program. remove
and erase
: As the beginning parameter we use function remove
, which finds all the spaces in the string, pushes them to the end of the container (in our case string s
), and returns beginning iterator of that "pushing", and the second parameter tells us to remove every single element of container from that beginning iterator to the end. I think this is really simple way to do it, but if it can't be useful to you, I am sorry for wasting your time reading all of this! :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.