C++ takes a string and outputs the characters in reverse order
- 2020-04-02 01:11:47
- OfStack
Using the character array method:
The basic idea is to determine the end flag of a character '\0' and then print forward from that position.
Implementation code:
#include<iostream>
using namespace std;
int main(){
char a[50];
cout<<"please input a string:";
cin>>a;
int i=0,k=0;
while(i<50){
if(a[i]=='0'){
k=i;
break;
}
i++;
}
cout<<"reverse order: ";
for(;k>=0;k--){
cout<<a[k];
}
cout<<endl;
return 0;
}
With string method:
The basic idea is to determine the length of a character through the strlen() function and then output from the position of that length in the array.
Implementation code:
#include<iostream>
#include<string>
using namespace std;
int main(){
char a[50];
cout<<"please input a string:";
cin>>a;
int k=0;
k=strlen(a);
cout<<"Reverse order: ";
for(;k>=0;k--){
cout<<a[k];
}
cout<<endl;
return 0;
}