【问题标题】:How to take a word from a file, and store it in a variable? C++如何从文件中取出一个单词,并将其存储在一个变量中? C++
【发布时间】:2017-10-16 19:35:45
【问题描述】:

我在 C++ 控制台应用程序中制作了一个简单的石头剪刀布游戏。到目前为止,游戏运行良好.. 直到我尝试将文件中的单词存储在变量中,然后尝试在 IF 语句中使用该变量。


这是我将文件中的单词存储在变量中的方式。

string comp_selection;
char player_selection;

这是我试图让它工作的代码部分。

cout << "Rock, Paper, or Scissors?";
cin >> player_selection;

if (comp_selection =='r' || comp_selection == 'R')
{
    if (player_selection == 'r' || player_selection == 'R')
    {
        cout << "Computer chose " << comp_selection << "... It's a draw!" << std::endl;
    }
    else if (player_selection == 'p' || player_selection == 'P')
    {
        cout << "Computer chose " << comp_selection << "... You win!" << std::endl;
    }
    else if (player_selection == 's' || player_selection == 'S')
    {
        cout << "Computer chose " << comp_selection << "... You lose!" << std::endl;
    }
}

输出应该是:

计算机选择了摇滚……你赢了!

例如,如果玩家选择了纸。 相反,我收到此错误消息

严重性代码描述项目文件行抑制状态 错误 C2678 二进制“==”:未找到采用“std::string”类型左侧操作数的运算符(或没有可接受的转换)

任何帮助或指导,都会很棒!提前谢谢了。

【问题讨论】:

  • 查看错误!!未找到采用“std::string”类型的左侧操作数的运算符。您正在将 char 与 std::string 进行比较

标签: c++ string variables


【解决方案1】:

您的comp_selection 被定义为std::string,但您将它与char'r' 等)进行比较。您应该将其与另一个字符串 ("r") 进行比较,或者将 comp_selection 重新定义为一个字符:

char comp_selection;
char player_selection;

在 C++ 中,单个字符由单引号 ('c') 表示,而字符串由双引号 ("full string") 表示。

【讨论】:

  • 该方法效果很好,但是,当我使用 char 方法输出消息时,输出只是读取字符串的第一个字母,而不是整个字符串。我想输出整个字符串。
【解决方案2】:

到目前为止,您一直在享受 cin &gt;&gt; 重载,认识到它正在写入 char。从文件中读取时,您显然使用了字符串。这很好,除了现在编译器抱怨它不知道如何比较stringchar。简而言之,您的类型不匹配。

【讨论】:

    【解决方案3】:

    您只能比较 comp_selection (comp_selection[0]) 的第一个字符

    if (comp_selection[0] =='r' || comp_selection[0] == 'R')
    {
    

    这不是最好的解决方案,但它需要最少的代码更改......

    【讨论】:

      【解决方案4】:

      我刚刚意识到我的代码做了它应该做的事情!通过设置我 comp_selectionchar,就像这里有人建议的那样,我可以使用 IF 语句手动输入计算机选择的内容。

      例如:

      if (comp_selection == 's' || comp_selection == 'S')
      {
          if (player_selection == 'r' || player_selection == 'R')
          {
              cout << "Computer chose Scissors... You win!" << std::endl;
          }
          else if (player_selection == 'p' || player_selection == 'P')
          {
              cout << "Computer chose Scissors... You lose!" << std::endl;
          }
          else if (player_selection == 's' || player_selection == 'S')
          {
              cout << "Computer chose Scissors... It's a draw!" << std::endl;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-11-05
        • 1970-01-01
        • 2016-01-24
        • 1970-01-01
        • 2011-07-03
        • 1970-01-01
        • 2020-06-24
        • 2020-08-17
        • 1970-01-01
        相关资源
        最近更新 更多