Search code examples
c++stringoopc++11palindrome

Trying to refresh my coding. Palindrome excercise giving me an issue. Googled my error but cant fix it.


I'm working on a c++ exercise and honestly knowledge on strings is a little foggy and probably why this isn't working. I've forgotten a lot syntactically but I have a good foundational understanding of OOP in general. Just trying to get back into the swing of things. Also I know my consistencies are weird with the std:: and then omitting it at places like cin haha. Just messing around. Thanks for your help.

#include <iostream>
#include <string>
std::string reverse(std::string s);
using namespace std;

int main(){

        std::string s;
        cin>>s;

        std::string n = reverse(s);
        if(n == s){
                std::cout<<"plindrome"endl;
        }
}


string reverse(string s){

        int n = s.length();

        for(int i = 0; i<n/2; i++){
                swap(s[i], s[n-1-1])
        }

        return s;

}

Solution

  • #include <iostream>
    #include <string>
    std::string reverse(std::string s);
    using namespace std;
    
    string reverse(string s) {
    
        int n = s.length();
    
        for (int i = 0; i<n / 2; i++) {
            swap(s[i], s[n - i - 1]);
        }
    
        return s;
    
    }
    
    int main() {
    
        std::string s;
        cin >> s;
    
        std::string n = reverse(s);
        if (n == s) {
            std::cout << "plindrome" << endl;
        }
    }
    

    just fixed the swap line so it should be s[i] and s[n - i - 1] and syntax error while printing