无法通过循环运行我的代码,但是手动复制和粘贴有效
Can't run my code though a loop however manually copying and pasting works
这段代码有效。我还可以在我的主文件中从头到尾复制粘贴几次,它仍然可以工作。
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 语句来处理。
相关文章:
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 如何在 Tensorflow C++ 中有效地复制一行
- 用于删除复制/移动分配运算符的有效签名
- 只有先复制到临时变量中时,传递对字符串的引用才有效
- 使用C++在 Linux 中复制文件的有效方法
- 使用memcpy将浮点数组复制到uint8_t的数组是否有效
- 将元素从一个向量复制到另一个向量的最有效方法,给定一个不被复制的索引列表
- 无法通过循环运行我的代码,但是手动复制和粘贴有效
- C++:向量中向量列表的有效复制
- 复制省略在默认函数参数中是否有效
- 指向static_cast有效以避免复制
- 引用或复制结构的结构(已分配的memset)是一件有效的事情
- 更有效地使用fork()和写时复制内存共享
- 在派生类构造函数中复制继承的成员有效吗
- 如何在C++中有效地将整个队列复制到向量/数组
- 用c++实现带掩码数组复制的有效方法
- 当我们进行复制初始化时,复制构造函数或构造函数是否有效
- 如何使数组变量指向不同的数组,有效地将第二个数组的内容复制到第一个数组中
- 为什么在复制构造函数中"copying"引用仍然有效?
- 这是一个有效的复制构造函数吗?