如何从文件中提取单词并将其存储在变量中?C++; 我在C++控制台上做了一个简单的石头、剪纸、剪刀游戏。到目前为止,这场比赛打得很好。。直到我尝试将文件中的单词存储在变量中,然后尝试在IF语句中使用该变量

如何从文件中提取单词并将其存储在变量中?C++; 我在C++控制台上做了一个简单的石头、剪纸、剪刀游戏。到目前为止,这场比赛打得很好。。直到我尝试将文件中的单词存储在变量中,然后尝试在IF语句中使用该变量,c++,string,variables,C++,String,Variables,下面是如何将文件中的单词存储在变量中 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

下面是如何将文件中的单词存储在变量中

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;
    }
}
cout>player\u选择;
if(comp_selection='r'| | comp_selection='r')
{
如果(玩家选择=='r'| |玩家选择=='r')
{

cout您的
comp_选择
被定义为
std::string
,但您正在将其与
字符
'r'
等)进行比较。您应该将其与另一个字符串(
“r”
)进行比较,或者将
comp_选择
重新定义为字符:

char comp_selection;
char player_selection;

<>在C++中,单个字符用单引号表示(<代码> c '< /COD>),而字符串由双引号表示(<代码>)满字符串“< /代码>”。.

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

您只能比较组合选择的第一个字符(组合选择[0])


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

我刚刚意识到,通过设置
comp_selection
char
,就像这里有人建议的那样,我可以使用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;
    }
}
if(comp_selection='s'| | comp_selection='s')
{
如果(玩家选择=='r'| |玩家选择=='r')
{

看不到错误!!找不到使用“std::string”类型左侧操作数的运算符…您正在将char与std::string进行比较。该方法非常有效,但是,当我使用char方法输出消息时,输出只读取字符串的第一个字母,而不是整个字符串。我希望输出整个字符串。
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;
    }
}