请给我建议C++回文循环

Please give me advise for C++ Palindrome loop

本文关键字:C++ 回文 循环      更新时间:2023-10-16
#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;
}

如何调整此代码以工作"Go Again(是/否(?"?

以及如何在同一行上设置答案,例如" DND 是一个回文。我目前的答案将是

"免打扰是一个回文。

谢谢

你忘了什么。这:

int main()
{
    {   

应该是这样的:

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

正如所写的那样,您的代码必不可少,曾经在一组大括号中运行过嵌套代码块。然后进入了一个没有身体的循环。即它做到了:

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;
}

并打印您提到的语句作为输出添加

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

紧接着getline声明。