chapter16test3

来源:互联网 发布:软件借贷不还会怎么样 编辑:程序博客网 时间:2024/05/17 03:13

这个题目用了好长时间,差点我都要放弃了,幸好把书看明白了,我的猜字游戏只用了三个单词: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
原创粉丝点击