使用数组的 C++ 回文程序
c++ palindrome program using arrays
我在使用第一个if语句时遇到问题,当程序进入循环时,它会跳过if语句。我的程序应该测试输入是否是回文,然后将其打印出来,("反向"数组只是在通过测试时向后打印出原始短语)。如果回文是"女士我是亚当",则输出应该是"女士",没有大写或标点符号。我不确定数组是否会解决这个问题,或者我是否需要另一个条件测试来删除这些字符?如果有人可以查看我的代码并告诉我出了什么问题/我能做什么,我将不胜感激。
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Variables and Arrays
char Phrase[80];
char Reverse[80];
char* Palindrome = Reverse;
int i, j, test = 1;
cout << "Please enter a sentence to be reversed: ";
cin >> Phrase;
cin.getline(Phrase, 80);
int length = strlen(Phrase);
for(i = 0; i < (length/2); i++) // do a loop from 0 to half the length of the string
{
if(test == 1) // test for palindrome
{
if(Phrase[i] != Phrase[length-i-1]) // check if the characters match
{
test = 0; // if they don't set the indicator to false
}
}
else
{
break; // if it is not a palindrome, exit the for loop
}
}
if(test == 1) //test to print out the phrase if it's a palindrome
{
cout << "Phrase/Word is a Palindrome." << endl;
for(j = strlen(Phrase) - 1; j >= 0; Palindrome++, j--)
{
*Palindrome = Phrase[j];
cout << "The reverse is: " << Reverse << endl << endl;
}
}
else
{
cout << "Phrase/Word is not a Palindrome." << endl;
}
system("Pause");
return 0;
}
你 使用赋值而不是使用相等
if(test = 1) //Logical error. which will always be true
//it should be
if(test == 1)
修改了您的代码以在下面工作
http://ideone.com/GnO6hB
平等与赋值
=
表示赋值,因此语句test = 1
将test
设置为 1。由于 int 到 bool 的转换,如果 test
不为零,它将转换为 true
。因此,在您的代码中,每个if(test...)
的计算结果都将true
要解决此问题,您应该使用 ==
来测试相等性。
你的逻辑在第一个循环中是错误的:test
初始化为 0 并且永远不会等于 1,所以第一个循环是无用的。试试这个
int test = 1;
相关文章:
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- C++ 回文程序总是给出 0(假)作为输出问题;我的代码哪里有问题?
- 程序以查找给定字符串中回文的子字符串的数量
- 如何创建一个程序来标识最长的子字符串回文,而不考虑字母大小写
- 测试回文时程序不会继续运行 (C++)
- 回文程序和条件跳转或移动取决于未初始化的值
- C 中的回文数程序
- 使用 C++ 的回文程序的不需要的输出
- 内联程序集 - 检查单词是否为回文
- 使用数组的 C++ 回文程序
- 回文程序中非常奇怪的问题
- C++回文程序
- 堆栈和队列回文程序
- 使用堆栈和队列的回文程序
- 在制作回文程序 C++ 时遇到困难
- 字符串回文程序不会忽略案例
- 我的回文程序给出了一个例外
- 不能在回文程序中输入多个字符串
- 回文程序和 C 样式字符串中不需要的字符
- 回文c++程序