我在不使用string.h的情况下写了一个C++回文.在没有 Do-While 循环的情况下,它可以正常工作.但是当我尝
I wrote a C++ Palindrome without using string.h. It works fine without the Do-While loop. But as i tried make a loop it prints the result many times
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
初始化变量
int i,j,len;
char exit[5]={'E','X','I','T',' '};
char a[20];
bool flag;
flag=true;
do
{
cout<<"Enter a string:";
cin>>a;
初始化检查字符
for(len=0;a[len]!=' ';++len);
从开始和结束检查输入
for(i=0, j=len-1 ; i<len/2;++i,--j)
{
if(a[j]!=a[i])
flag=false;
}
如果它们不相等,则条件为假
if(flag!=true)
如果它们相等,那么它是回文
cout<<"nThe string is Palindrome "<<endl;
else
cout<<"nThe string is not Palindrome "<<endl;
}while(a[i]!=exit[i]);
当用户输入等于"EXIT"时,循环结束
cout<<"nnGood Bye and Take Care..!!"<<endl;
}
简化函数以更好地查看流程可能会很有用。您的代码类似于以下代码:
char exit[5]={'E','X','I','T',' '};
char a[20];
do {
cout<<"Enter a string:";
cin>>a;
printIfPalendrome();
} while(a[i]!=exit[i]);
这意味着 printIfPalendrome(( 将始终打印多次,因为它将针对 a[] 的每个索引打印。 这是因为 while 子句的行为不是您想要的。
我不知道
你为什么不想使用 cstring,但无论如何......如果你想检查某个字符串是否等于另一个字符串,它们应该有 sam ASCII 范围 - 所以 EXIT != exit,这就是为什么我使用 cctype 的 toupper(( 的原因。我添加了一些注释,在我看来你有糟糕的代码。在这里:
#include <iostream>
#include <conio.h>
//for using toupper()
#include <cctype>
using namespace std;
//void main() - main must return integer in the end of working
int main()
{
//initializing the variables
int i,j,len;
//exit is function from <cstdlib>, so it is better to use some other word
char stop[5]={'E','X','I','T',' '};
char a[20];
bool flag;
//additional variable to check if the word is 'exit'
bool check_exit = true;
do {
//for every new word you have to set flag befor compare
flag = true;
cout<<"Enter a string:";
cin>>a;
for(len=0;a[len]!=' ';++len);
//this is an example how to control end of program without strcmp or cstring library
if(len<5){ //we compare with 5-long array stop[]
for(i=0;i<len+1;++i){
if(toupper(a[i])!=stop[i]){
check_exit = true;
break;
} else check_exit = false; //end program
}
}
for(i=0, j=len-1 ; i<len/2;++i,--j){
if(a[j]!=a[i]){
flag=false;
break; //if only one character is wrong the rest is dosen't metter
}
}
//if(flag!=true) - wrong logic
if(flag)
cout<<"nThe string is Palindrome "<<endl;
else
cout<<"nThe string is not Palindrome "<<endl;
}while(check_exit);
cout<<"nnGood Bye and Take Care..!!"<<endl;
return 0;
}
相关文章:
- 如何在不知道C++中有多少可选参数的情况下在循环中使用va_arg?
- 循环依赖,在继承类的情况下使用覆盖方法
- C++在不使用pow或循环的情况下计算一个数字的幂
- 如何在不循环的情况下使用getline读取文件
- 如何在没有同步的情况下使用多个线程(2、4,8、16 个线程)在循环(10,100、1000 个周期)中打印字符串?
- 如何在没有可变参数函数的情况下循环函数的参数
- 如果 return 语句在带括号的循环中,错误可能会到达非 void 函数的末尾,但不会显示在没有括号的循环的情况下
- 在给定相同的输入的情况下,某些代码怎么可能花费更多时间来运行,这似乎只是因为它处于循环中?
- 如何在不中断整个循环的情况下跳过循环交互 - C++
- 如何在不停滞主循环的情况下实现对话系统?
- 如何在不将其拆分为两个嵌套循环的情况下打印整个形状?
- 了解如何在不冻结事件循环的情况下在 QThread 中休眠/等待
- 视觉 在C++中,我试图在没有递归的情况下循环访问许多对象
- 默认情况下,C++ 开关运行时循环
- while 循环是否在设置标志的情况下运行多次?
- 有没有办法在不使用循环的情况下非具体地引用映射中的每个值?C++
- 我可以在不循环访问数组/向量的情况下检查数组/向量中的单词吗?
- 您可以在没有列表或向量的情况下循环访问类对象吗?
- 这段代码如何在没有任何循环语句或'goto'或递归的情况下循环?
- 我如何在没有获得 EOF 的情况下循环通过 ifstream::get