C++ primer plus第六版课后编程题答案16.3


 

main163.cpp

#include <iostream>
#include <string>
#include <ctime>
#include <cctype>
#include <cstdlib>
#include <fstream>
using namespace std;
static const int NUM=26;

static string getTarget(int n)
{
	
	ifstream fin;
	fin.open("str.txt");
	if(fin.fail())
	{
		cout<<"error open the str.txt";
	}
	int m=n+1;//n有可能是0
	string target;
	while(m--)
	{	
		
		fin>>target;
		//cout<<target<<endl;
		//cin.get();//吃掉回车,居然不用吃掉回车,难道是因为fin中的>>会默认丢掉回车符
	}

	fin.close();
	return target;



}

void main163()
{


	srand(time(0));
	char play;
	cout<<"Will you play a word game?<Y/N>";
	cin>>play;
	play=tolower(play);
	/*测试
	string str=getTarget(10);
	string str1=getTarget(9);
	cout<<str<<endl;
	cout<<str1<<endl;
	*/
	while(play=='y')
	{
		//string target=getTarget(rand()%NUM);//余数可能是0
		string target=getTarget(2);
		int length=target.length();
		string attempt(length,'-');
		string badchars;
		int guesses=6;
		cout<<"Guess my secret word.It has "<<length
			<<" letters ,and you guess"<<endl
			<<" one letteer at a time:You get "<<guesses
			<<" wrong guesses "<<endl;

		while(guesses>0&&attempt!=target)
		{
			char letter;
			cout<<"Guess a letter:";
			cin>>letter;
			if(badchars.find(letter)!=string::npos||attempt.find(letter)!=string::npos)
				//如果曾经找过了
			{
				cout<<"You already guessesd that.Try anain"<<endl;
				continue;
			}	

			int loc=target.find(letter);
			if(loc==string::npos)//猜测错误
			{
				cout<<"Oh,bad guess!"<<endl;
				guesses--;
				badchars+=letter;
			}
			else
			{
				cout<<"Good guess!"<<endl;
				attempt[loc]=letter;
				loc=target.find(letter,loc+1);//检测后面还有没有该字符
				while(loc!=string::npos)
				{
					attempt[loc]=letter;
					loc=target.find(letter,loc+1);
				}
			}

			cout<<"Your word:"<<attempt<<endl;
			if(attempt!=target)
			{
				if(badchars.length()>0)
					cout<<"Bad choices:"<<badchars<<endl;
				cout<<"Guess "<<" bad "<<guesses<<" left "<<endl;	
			}
		}
		if(guesses>0)
			cout<<"That's right:"<<endl;
		else
			cout<<"Sorry,that word is "<<target<<endl;
			cout<<"Will you play another ?<Y/N>:";
			cin>>play;
			play=tolower(play);
		

	}


	cin.get();

}

str.txt

apiary
beetle
cereal
danger
ensign
florid
garage
health
insult
jackal
keeper
loaner
manage
nonce
onset
plaid
quilt
remote
stolid
train
useful
valid
whence
xenon
yearn
zippy

 

 


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注