我有一個關於C++的快速問題。我正在製作一個基於文本的遊戲,我希望玩家能夠輸入"Score"
,它會打印當前得分(int score = 50
)。我使用if(Choice == 3)
作爲數字,但我希望能夠在輸入中輸入單詞。C++:顯示變量
任何人都可以幫忙嗎?
感謝您的閱讀。
我有一個關於C++的快速問題。我正在製作一個基於文本的遊戲,我希望玩家能夠輸入"Score"
,它會打印當前得分(int score = 50
)。我使用if(Choice == 3)
作爲數字,但我希望能夠在輸入中輸入單詞。C++:顯示變量
任何人都可以幫忙嗎?
感謝您的閱讀。
使用std::getline
可將整行讀入字符串,然後將該字符串與==
進行簡單比較。
還有很多其他方法可以做到這一點,但任何不基於std::getline
的解決方案可能是不必要的複雜。
std::string input;
cin >> input;
// lowercase it, for case-insensitive comparison
std::transform(input.begin(), input.end(), input.begin(), std::tolower);
if (input == "score")
std::cout << "Score is: " << score << std::endl;
用於添加代碼以轉換爲全部小寫的+1。 –
很難猜出你想要做什麼,但是一般情況下,如果你想比較字符串,你可以使用字符串比較例程。例如
#include <iostream>
int main(void) {
std::string choice;
std::cout<<"Please enter your choice:"<<std::endl;
std::cin>>choice;
if (choice.compare("score")==0) {
std::cout << "score!" << std::endl;
}
else {
std::cout << "fail!" << std::endl;
}
}
如果使用boost,則可以執行不區分大小寫的比較。或者您可以將輸入轉換爲全部小寫。 Google「不區分大小寫的字符串比較C++」以獲取更多信息。
嘗試:
std::string userInput;
// Takes a string input from cin and stores in userInput variable
getline(std::cin, userInput);
// Check if user input is "Score"
if (userInput.compare("Score") == 0)
{
std::cout << "Score = " << score << std::endl;
}
如果用戶輸入的是「分數」,那麼比較將是精確匹配,和userInput.compare()將返回0,這就是爲什麼我們檢查,如果其爲零。
讀入字符串,並做一個(可能不區分大小寫)比較。 –