玩家 1 輸入單詞 → 程序打亂字母順序 → 玩家 2 猜原單詞。直到猜中顯示祝賀。
secretWordmixLetters(secretWord) 返回 mixedWordsecretWordstring mixLetters(string word) {
string mixed;
srand(time(0)); // 僅主程序調用一次
while (!word.empty()) {
int pos = rand() % word.size(); // 隨機索引
mixed += word[pos]; // 追加到新串
word.erase(pos, 1); // 從原串刪除該字符
}
return mixed;
}
srand(time(0)) 初始化偽隨機種子(全程一次)rand() % n 生成 0~n-1 隨機數string::erase(pos, 1) 刪除指定位置 1 個字符do-while 保證至少猜一次int main() {
string secret, mixed, guess;
srand(time(0));
cout << "輸入一個單詞: "; cin >> secret;
mixed = mixLetters(secret);
do {
cout << "原先的單詞是什麼? " << mixed << endl;
cin >> guess;
if (guess == secret) cout << "猜對了!好棒!" << endl;
else cout << "猜錯了!" << endl;
} while (guess != secret);
return 0;
}
綜合運用:變量、字符串、函數、隨機數、循環、條件、I/O、文件操作(擴展)。是從「語法學習」到「程序設計」的關鍵一步。