C++ Primer 第3章ex 3.7

#include <string>
#include <iostream>
using namespace std;
void compareStr();
void compareStrSize();
int main()
{
   
	while(true)
	{
		cout << endl << "1) 测试两个string对象是否相等" << endl;
		cout << "2) 测试两个string对象的长度是否相等" << endl;
		cout << "3) 退出" << endl << endl;
		cout << "请选择 [1], [2] or [3]: ";
		string userInput; 
		
		getline(cin,userInput);
		
		if(userInput.size() == 0) continue;

		const char ch = userInput[0];

		if(ch == '3') break;
		else if(ch =='1') compareStr();
		else if(ch == '2') compareStrSize();
		else cout << endl << "Input error. Enter 1, 2 or 3 and [Enter]."<< endl;
	}

	

	return 0;
} 
void compareStr()
{
	string str1,str2;
	cout<<"请您输入str1的数据"<<endl;	
	cin>>str1;
	cout<<"请您输入str2的数据"<<endl;	
	cin>>str2;
	if (str1==str2)
	{
		cout<<"str1与str2相等"<<"其中str1="<<str1<<endl<<"str2="<<str2<<endl;
	}else
	{
		cout<<(str1>str2?str1:str2)<<endl;
	}
}

void compareStrSize()
{
	string str1,str2;
	cout<<"请您输入str1的数据"<<endl;	
	cin>>str1;
	cout<<"请您输入str2的数据"<<endl;	
	cin>>str2;
	if (str1.size()==str2.size())
	{
		cout<<"str1与str2的长度相等"<<"其中str1的长度为:"<<str1.size()<<endl<<"str2的长度为:"<<str2.size()<<endl;
	}else
	{
		cout<<(str1.size()>str2.size()?str1:str2)<<endl;
	}
}

原文地址:https://www.cnblogs.com/fuyou/p/2741878.html