C++:显示变量

C++: Displaying a Variable

本文关键字:变量 显示 C++      更新时间:2023-10-16

我有一个关于C++的快速问题。我正在制作一个基于文本的游戏,我希望玩家能够输入"Score",它将打印当前分数(int score = 50)。我正在使用if(Choice == 3)表示数字,但我希望能够在输入中键入单词。

谁能帮忙?

感谢您的阅读。

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;

使用 std::getline 将整行读入字符串,然后简单地将字符串与 == 进行比较。

还有许多其他方法可以做到这一点,但任何不基于std::getline的解决方案都可能是不必要的复杂。

很难

准确猜测您要做什么,但一般来说,如果要比较字符串,请使用字符串比较例程。例如

#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,则可以进行不区分大小写的比较。或者,您可以将输入转换为全部小写。谷歌"不区分大小写的字符串比较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;
}

如果用户输入是"Score",那么比较将是完全匹配的,userInput.compare()将返回0,这就是为什么我们检查它是否为零。