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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值