chapter16test3

这个题目用了好长时间,差点我都要放弃了,幸好把书看明白了,我的猜字游戏只用了三个单词:apiary,bettle,cereal;程序主要修改的地方是:文件读取+push_back()+size(),程序在下边

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<vector>
#include<algorithm>
#include<ctime>
using namespace std;
int main()
{
char play;
ifstream infile;
infile.open("guess.txt");
if (!infile.is_open())
{
cout << "File can't open.\n";
exit(EXIT_FAILURE);
}
vector<string> wordlist; string temp;
infile >> temp;
while (infile)
{
wordlist.push_back(temp);
infile>>temp;
}

cout << "Will you play a guess game<y/n>:";
while (cin >> play&&play == 'y')
{
int num = wordlist.size();
string target=wordlist[rand()%num];
cout << "Target= " << target<< endl;
int length = target.size();
string attempt(length, '-');
string badchars;
int guess = 6;
cout << "Guess my secrect word,it has " << length << " letters,you have " << guess << " wrong times.\n";
cout << "Your word style :" << attempt << endl;
while (guess > 0 && attempt != target)
{
char letter;
cout << "Guess a letter :"; cin >> letter;
if (badchars.find(letter) != string::npos || attempt.find(letter) != string::npos)
{
cout << "You have already guessed it.\n";
continue;
}
int loc = target.find(letter);
if (loc == string::npos)
{
cout << "Bad guess .\n";
guess--;
badchars += letter;
}
else
{
cout << "Good guess .\n";
attempt[loc] = letter;
loc = target.find(letter, loc + 1);
while (loc != string::npos)
{
attempt[loc] = letter;
loc = target.find(letter, loc + 1);
}
}
cout << "You word :" << attempt << endl;
if (attempt != target)
{
if (badchars.length() > 0)
cout << "Bad choice :" << badchars << endl;
cout << guess << " wrong guess left .\n";
}
}
if (guess > 0)
cout << "That's right .\n";
else
cout << "Sorry the word is " << target << endl;
cout << "Will you play another ?";
}
cout << "Finished !\n";
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值