我在不使用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

本文关键字:情况下 循环 Do-While 工作 常工作 C++ string 回文 一个      更新时间:2023-10-16
     #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;

}

相关文章: