gpt4 book ai didi

c++ - 回文程序不能输入多个字符串

转载 作者:太空狗 更新时间:2023-10-29 23:08:46 24 4
gpt4 key购买 nike

#include <iostream>
#include <ctype.h>

using namespace std;

void isPalindrome();

int main()
{
char response;
isPalindrome();
cout << "Input another string(y/n)?" << endl;
cin >> response;
response = toupper(response);
if (response == 'Y')
isPalindrome();

return 0;
}

void isPalindrome()
{
char str[80], str2[80];
int strlength;
int j = 0;
int front, back;
bool flag = 1;

cout << "Input a string:" << endl;
cin.getline(str, 80);
strlength = strlen(str);

for (int i = 0; i < strlength; i++)
{
if (islower(str[i]))
str[i] = toupper(str[i]);
}

for (int i = 0; i < strlength; i++)
{
if (isalpha(str[i]))
{
str2[j] = str[i];
j++;

}
}

str2[j] = '\0';
front = 0;
back = strlength - 1;

for (int i = 0; i < j / 2; i++)
{
if (str2[front] != str2[back])
{
flag = 0;

break;
}
}

if (!(flag))
cout << "It is not a palindrome" << endl;
else
cout << "It's a palindrome" << endl;

cout << "str: " << str << " str2: " << str2 << " strlength: " << strlength << " j: " << j << endl;
cout << "front: " << front << " back: " << back << " flag: " << flag << endl;
}

我只是想知道是否有人可以帮助向我解释为什么我的代码无法正常工作。

我可以运行一次就很好,我得到了正确的答案,但是当提示询问我是否要输入另一个字符串并且我键入 'y' 时,提示只是跳过输入并自行终止。

我尝试了 cin.ginore('\n', 80),但这只是给了我一堆空白行。我在末尾添加了一些代码来检查值,它们都转到 0 并删除字符串。

也许是指向系统如何处理内存的正确解释的链接?

编辑:第二次运行输入序列时,我一直遇到同样的问题。输出看起来像这样:

    Input a string:
Radar
It's a palindrome
Input another string(y/n)?
y


_ <- this being my cursor after pressing enter 3 times

我将从头开始重新构建程序,并尝试在没有函数的情况下进行。我仍然希望链接到解释如何使用现代 C++ 处理用户输入的页面。

最佳答案

问题在于:

cin >> response;

这会将用户输入的 y/n 读取到变量 response 中,但是在输入缓冲区中会留下一个换行符,由 getline 使用 isPalindrome 函数。

要解决此问题,您需要在读取用户响应后从输入缓冲区中删除换行符。您可以使用:

cin >> response;
std::cin.ignore(INT_MAX);

通过上述修复,您可以重试一次回文检查。为了使多次重试成为可能,您需要一个循环。我建议在您的主程序中使用 do-while 循环:

char response;
do {
isPalindrome();
cout << "Input another string(y/n)?" << endl;
cin >> response;
std::cin.ignore(INT_MAX);
response = toupper(response);
} while(response == 'Y');

关于c++ - 回文程序不能输入多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8251908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com