C++ primer ex 3.8

#include <string>
#include <iostream>

using namespace std;

void connstring()
{
	cout<<"请输入字符串(#结束):"<<endl;
	string resultStr,userInputStr;

	while(cin>>userInputStr)
	{
		if (!userInputStr.compare("#"))
		{
			break;
		}
	resultStr+=userInputStr;
	}
	cout<<"连接后的字符:"<<resultStr<<endl;

}

void connstringwithspace()
{
	cout<<"请输入字符串(#结束):"<<endl;
	string resultStr,userInputStr;
	cin>>resultStr;
	while(cin>>userInputStr)
	{
		if (!userInputStr.compare("#"))
		{
			break;
		}
		resultStr=resultStr+" "+userInputStr;
	}
	cout<<"连接后的字符:"<<resultStr<<endl;

}

int main()
{

	while(true)
	{

		cout << endl << "1) 输出连接后的字符串(两两之间无任何空格)" << endl;
		cout << "2) 输出连接后的字符串(两两之间有空格)" << endl << 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') connstring();
		else if(ch =='2') connstringwithspace();
		else cout << endl << "Input error. Enter 1, 2 or 3 and [Enter]."<< endl;
	}

	return 0;
}

posted on 2012-10-26 21:12  零风腾飞  阅读(157)  评论(0编辑  收藏  举报

导航