用字符數組方法:
基本思路是,先判斷字符的結束標志'\0',然后從該位置向前輸出。
實現代碼:
#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; }
用string方法:
基本思路是,通過strlen()函數判斷字符的長度,然后從數組該長度的位置輸出。
實現代碼:
#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; }