1. 程式人生 > 其它 >用指標處理比較字串的大小

用指標處理比較字串的大小

技術標籤:筆記c++字串

題目

要求使用指標處理下面的問題,輸入四個整數,按由小到大的順序輸出;然後將程式改為:輸入四個字串,按由小到大順序輸出。

整數大小比較

#include<iostream>
using namespace std;
void swap(int*, int*);
int main()
{
	
	int a, b, c, d;
	cout << "請輸入四個整數:";
	cin >> a >> b >> c >> d;
	//這裡我使用了感覺笨笨的方法進行比較,待日後學習更多
	if
(a > b) swap(&a, &b); if (b > c) swap(&b, &c); if (a > b) swap(&a, &b); if (c > d) swap(&c, &d); if (b > c) swap(&b, &c); if (a > b) swap(&a, &b); cout << "由小到大排序:"; cout << a << "/t"<<
b <<"/t"<< c <<"/t"<< d << endl; return 0; } void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; }

列印結果
在這裡插入圖片描述

字串大小比較

通過更改上面的程式碼。

#include<iostream>
using namespace std;
void swap(string*, string*);
int main()
{
	/*要求使用指標處理下面的問題,輸入四個整數,
	按由小到大的順序輸出;然後將程式改為:輸入四個字串,
	按由小到大順序輸出。*/
string a, b, c, d; cout << "請輸入四個字串:"; cin >> a >> b >> c >> d; if (a > b) swap(&a, &b); if (b > c) swap(&b, &c); if (a > b) swap(&a, &b); if (c > d) swap(&c, &d); if (b > c) swap(&b, &c); if (a > b) swap(&a, &b); cout << "由小到大排序:"; cout << a << " "<< b <<" "<< c <<" "<< d << endl; return 0; } //變數交換 void swap(string* a, string* b) { string temp = *a; *a = *b; *b = temp; }

列印結果
在這裡插入圖片描述

更改過程中,起初將int改為char,無法比較多個字母的字串,故改為string型別

C++初學者還望大家指正。