学会熟练运用C++类string中常用的一些函数来解决问题
#include<iostream>
#include<string>
#include<cstdlib>
#include<ctime>
#include<cctype>
#include"windows.h"
using namespace std;
const int num = 12;
int main()
{
string str[num] = { "january", "february", "march", "april", "may", "june",
"july", "august", "september", "octomber", "november", "december" };
srand(time(0));
char choice;
cout << "Let's to start a guess word game<y/n>\n";
(cin >> choice).get();
choice = toupper(choice);
while(choice == 'Y')
{
string target = str[rand() % num];
int len = target.size();
int count = 6;
string guess(len, '-');
char ch;
cout << "please input a alphabet you guess: " << endl;
(cin >> ch).get();
while (count&&guess != target)
{
if (target.find(ch) == string::npos)
{
--count;
cout << "This alphabet is not in target string." << endl;
if (count <= 0)
{
cout << "Sorry, your chance is run out of.\n";
}
}
else
{
cout << "This a right alphabet\n";
int index = target.find(ch);
while (index!=string::npos)
{
guess[index] = ch;
index = target.find(ch, index+1);
}
}
cout << "Now, the guess string is **" << guess << "**"<<endl;
if (guess == target) break;
cout << "please input a new alphabet you guess: " << endl;
(cin >> ch).get();
}
if (count>0)
{
cout << "Congratulation! you all right.\n"
<< "target string is " << guess << endl;
}
cout << "Do you continue?<y/n>" << endl;
(cin >> choice).get();
choice = toupper(choice);
}
cout << "OK! Game over\n";
system("pause");
return 0;
}
程序运行结果如下