无法通过循环运行我的代码,但是手动复制和粘贴有效

Can't run my code though a loop however manually copying and pasting works

本文关键字:复制 有效 循环 运行 代码 我的      更新时间:2023-10-16

这段代码有效。我还可以在我的主文件中从头到尾复制粘贴几次,它仍然可以工作。

int main()
{
string str;
cout << "Input a palindrome: "; // Start
getline(cin, str);
if (testPalindrome(str) == 1)
    cout << "Your input is a palindrome: True" << endl;
else
    cout << "Your input is a palindrome: False" << endl;
cout << endl; // End

cout << "nCreated by,nNorman Ettedgui" << endl;
system("pause");
return 0;
}

但是,这段代码将不起作用,我得到的错误是我的函数中的字符串越界(奇怪的是在函数调用之前)。

这是我的测试回文函数:

bool testPalindrome(string str)
{
string newStr;
for (int i = 1; i < str.length() - 1; i++)
    newStr += str[i];
if (newStr.length() > 1)
    testPalindrome(newStr);
if (str[0] == str[str.length() - 1])
    return true;
}

这是我正在尝试运行的:

int main()
{
string str;
int i = 0;
while (i != -1)
{
    cout << "Input a palindrome: ";
    getline(cin, str);
    if (testPalindrome(str) == 1)
        cout << "Your input is a palindrome: True" << endl;
    else
        cout << "Your input is a palindrome: False" << endl;
    cout << "-1 to Exit or any other number to continue: ";
    cin >> i;
    cout << endl;
}
cout << "nCreated by,nNorman Ettedgui" << endl;
system("pause");
return 0;
}

尝试以下函数

bool testPalindrome( string s)
{
   return ( s.size() < 2 ? true 
                         : s.front() == s.back() && testPalindrome( s.substr( 1, s.size() -2 ) ) );
} 

也主要代替此声明

if (testPalindrome(str) == 1)

if ( testPalindrome(str) )

如果您同时使用 getline 和运算符>>那么您应该使用忽略跳过 ENTER 键(不要忘记包括<limits>

#include <limits>
while (i != -1)
{
    cout << "Input a palindrome: ";
    cin.ignore( numeric_limits<streamsize>::max() );
    getline(cin, str);
    //...
    cin >> i;
    cout << endl;
}

我将向您解释为什么会出现错误。如果没有带有忽略函数 getline 调用的语句,则读取一个空字符串。所以str是空的。在功能测试回文中有语句

for (int i = 1; i < str.length() - 1; i++)

对于空字符串,其长度等于 0 则表达式

str.length() - 1
具有无符号

类型的最大值,因为此表达式的类型是某个无符号整型类型,并且 -1 的内部表示形式对应于最大无符号值。所以变量 i 将始终小于 -1,并且您会收到内存访问冲突。

此外,我将使用另一个循环而不使用其他变量 i。

while ( true )
{
       cout << "Input a palindrome: ";
       string str;
       getline(cin, str);
       if ( str.empty() ) break;
       //...
} 

if (newStr.length()>1)只处理 newStr.length() 为>1 的条件。当条件:if (newStr.length()>1)为 false 时,您需要一个 else 语句来处理。