我一直在Cpp上玩Hang子手遊戲...... 所以我創建了一個名爲SoFar
的變量,它在起始處存儲破折號,但是逐漸被發現。字符串沒有被正確打印/初始化
for(i = 0; i <= TheWord.length(); i++)
SoFar[i] = '-';
所以,我(試圖)初始化SoFar
包含在首發破折號,並且具有相同的長度爲TheWord
後來,當我打印SOFAR,它只是空的!
cout << "\nSo far, the word is : " << SoFar << endl;
任何和所有的建議表示讚賞。這是我的完整方案,以供參考:
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <ctime>
#include <cctype>
using namespace std;
int main()
{
vector<string> words;
words.push_back("SHAWARMA");
words.push_back("PSUEDOCODE");
words.push_back("BIRYANI");
words.push_back("TROLLED");
srand((unsigned)time(NULL));
string TheWord = words[(rand() % words.size()) + 1];
string SoFar;
const int MAXTRIES = 8;
string used = "";
int tries, i;
i = tries = 0;
char guess;
for(i = 0; i <= TheWord.length(); i++)
SoFar[i] = '-';
while(tries <= MAXTRIES && SoFar != TheWord)
{
/****************************************************************/
/* I/0 */
/****************************************************************/
cout << "\nYou haz " << MAXTRIES - tries << " tries to go!\n" ;
cout << "You've used the following letters : ";
for(i = 0; i <= used.length(); i++)
cout << used[i] << " : " ;
cout << "\nSo far, the word is : " << SoFar << endl;
cout << "\nEnter your guess : " ;
cin >> guess;
/****************************************************************/
/* Processing input */
/****************************************************************/
if(used.find(guess) != string::npos)
continue;
guess = toupper(guess);
if(TheWord.find(guess) != string::npos)
{
for(i = 0; i <= TheWord.length(); i++)
{
if(guess == TheWord[i])
SoFar[i] = guess;
}
}
else
{
cout << "\nSorry, but the word doesn't have a letter like " << guess << " in it...\n";
tries++;
}
used += guess;
}
if(tries == MAXTRIES)
cout << "\nYep, you've been hanged...\n";
else if(SoFar == TheWord)
cout << "\nYou got it! Congratulations...\n(Now Im gonna add some psuedorandomly generated words just for you <3 :P)";
cout << "\nThe word was : " << TheWord;
return 0;
}
你建議我應該怎麼做? –
使用填充構造函數'string(size_t n,char c);'。 –