Rich
Rich

Reputation: 21

Please give me advise for C++ Palindrome loop

#include <string>
#include <algorithm>
#include <iostream>
#include <conio.h>
#include <cctype>

using namespace std; 

int main()
{

    {   
        system("cls");
            cout << "\nEnter a palindrome." << endl;
            std::string str; 
            getline(std::cin, str);

             if( equal(str.begin(), str.end(), str.rbegin()) ) 
                std::cout << "is a palindrome!\n";

             else 
                std::cout << "is not a palindrome!\n"; 

            cout << "\nGo again (Y/N)?" << endl;


    } while (toupper(_getch()) !='N');


    return 0;

}

How can I adjust this code to work Y of "\nGo again (Y/N)?"?

and how to set answer on the same line like " DND is a palindrome." My current answer's gonna be

"DND is a palindrome."

Thank you

Upvotes: 1

Views: 210

Answers (1)

WhozCraig
WhozCraig

Reputation: 66194

You forgot something. This:

int main()
{
    {   

should be this:

int main()
{
    do {   // <==== see added keyword?

As written you're code essential ran a nested code block in a set of curly braces once. Then entered into a while-loop with no body. I.e. it did this:

int main()
{
    // this just started a nested scope block
    {
        system("cls");
        cout << "\nEnter a palindrome." << endl;
        std::string str;
        getline(std::cin, str);

        if( equal(str.begin(), str.end(), str.rbegin()) )
            std::cout << "is a palindrome!\n";

        else
            std::cout << "is not a palindrome!\n";

        cout << "\nGo again (Y/N)?" << endl;
    }
    // and now the nested scope block is closed


    // now we enter a completely unrelated while-loop with no body.
    while (toupper(_getch()) !='N');

    return 0;
}

and to print the statement you mentioned as output add

std::cout<<endl<<str<<" ";

immediately after getline statement.

Upvotes: 1

Related Questions