C++輸入一個(gè)字符串,把其中的字符按照逆序輸出的兩種方法解析
更新時(shí)間:2013年07月24日 08:48:46 作者:
以下是對(duì)C++中輸入一個(gè)字符串,把其中的字符按照逆序輸出的兩種方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過來參考下
用字符數(shù)組方法:
基本思路是,先判斷字符的結(jié)束標(biāo)志'\0',然后從該位置向前輸出。
實(shí)現(xiàn)代碼:
復(fù)制代碼 代碼如下:
#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()函數(shù)判斷字符的長度,然后從數(shù)組該長度的位置輸出。
實(shí)現(xiàn)代碼:
復(fù)制代碼 代碼如下:
#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;
}
相關(guān)文章
深入解析C++編程中基類與基類的繼承的相關(guān)知識(shí)
這篇文章主要介紹了C++編程中基類與基類的繼承的相關(guān)知識(shí),包括多個(gè)基類繼承與虛擬基類等重要知識(shí),需要的朋友可以參考下2016-01-01

