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
——————————————————————————————————————————————————
//写的错误或者不好的地方请多多指导,可以在下面留言或者给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。
转载请注明出处:https://www.royalchen.com/
author:royalchen
Email:royalchen@royalchen.com
———————————————————————————————————————————————————