C++ Primer 第3章ex3.5

#include <string>
#include <iostream>
using namespace std;
void getInputLine();
void getInputWord();
int main()
{
   
	while(true)
	{
		cout << endl << "1) 每次从标准输入中读入一行文本" << endl;
		cout << "2) 每次从标准输入中读入一个单词" << 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') getInputLine();
		else if(ch == '2') getInputWord();
		else cout << endl << "Input error. Enter 1, 2 or 3 and [Enter]."<< endl;
	}

	

	return 0;
} 
void getInputLine()
{
	cout<<"请您输入数据"<<endl;
	string in;
	while (getline(cin,in))
	{
		cout<<"用户输入:"<<in<<endl;
		if(!in.compare("#"))
			break;
	}
}

void getInputWord()
{
	cout<<"请您输入数据"<<endl;
	string in;
	while (cin>>in)
	{
		cout<<"用户输入:"<<in<<endl;
		if(!in.compare("#"))
			break;
	}
}

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