【问题标题】:C++: Displaying a VariableC++:显示变量
【发布时间】:2014-03-25 05:39:49
【问题描述】:

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

谁能帮忙?

感谢阅读。

【问题讨论】:

  • 读入字符串,并进行(可能不区分大小写)比较。

标签: c++ variables int


【解决方案1】:
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;

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      很难准确地猜出你想要做什么,但一般来说,如果你想比较字符串,你会使用字符串比较例程。例如

      #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++”了解更多信息。

      【讨论】:

        【解决方案4】:

        试试:

        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,这就是我们检查它是否为零的原因。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-06
          • 1970-01-01
          • 1970-01-01
          • 2015-09-29
          • 2020-08-23
          • 1970-01-01
          相关资源
          最近更新 更多