C++輸入一個字符串,把其中的字符按照逆序輸出的兩種方法


用字符數組方法:

基本思路是,先判斷字符的結束標志'\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;
	
} 



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM