修改下列程序,使之从文件中读取单词。一种方案是,使用vector<string>对象而不是string数组。这样便可以使用push_back()将数据文件中的单词复制到vector<string>对象中,并使用size()来确定单词列表的长度。由于程序应该每次从文件中读取一个单词,因此应使用运算符>>而不是getline()。文件中包含的单词应该用空格、制表符或换行符分隔。
// hangman.cpp -- some string methods #include <iostream> #include <string> #include <cstdlib> #include <ctime> #include <cctype> using std::string; const int NUM = 26; const string wordlist[NUM] = {"aplary", "beetle", "cereal", "danger", "ensign", "florid", "garage", "health", "insult", "jackal", "keeper", "loaner", "manage", "nonce", "onset", "plaid", "quilt", "remote", "stolid", "train", "useful", "valid", "whence", "xencn", "yearn", "zippy"};
int main() { using std::cout; using std::cin; using std::tolower; using std::endl; std::srand(std::time(0)); char play; cout << "Will you play a word game? <y/n> "; cin >> play; play = tolower(play); while (play == 'y') { string target = wordlist[std::rand() % NUM]; int length = target.length(); string attempt(length, '-'); string badchars; int guesses = 6; cout << "Guess my secret word. It has " << length << " letters, and you guess\n" << " one letter at a time. You get " << guesses << " wrong guesses.\n"; cout << "Your word: " << attempt << 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 guessed taht. Try again.\n"; continue; } int loc = target.find(letter); if (loc == string::npos) { cout << "Oh, bad guess!\n"; --guesses; badchars += letter; // add to string } else { cout << "Good guess!\n"; attempt[loc]=letter; // check if letter appears again 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 << guesses << " bad guesses left\n"; } } if (guesses > 0) cout << "That's right!\n"; else cout << "Sorry, the word is " << target << ".\n"; cout << "Will you play another? <y/n> "; cin >> play; play = tolower(play); }
cout << "Bye\n";
return 0; }