c++中Char到Int的转换问题

Problems Converting Char to Int in C++

本文关键字:转换 问题 Int Char c++      更新时间:2023-10-16

我正试着玩这个剪刀石头布游戏,但是我无法通过"您已进入line"这条线。

我的教授说我的问题是,当randNumGenerated是int类型时,userChoice是char类型。我试着用下面的代码来转换r,p和s的值:Char r = 'a';Int a = r;

但是得到了"重新定义:不同的基本类型";编译器错误。我不确定该怎么做,因为将变量重新定义为int是我的意图。我想错了吗?如有任何帮助,不胜感激!

int main()
{
    char userChoice;
    int computer;
    int randNumGenerated = 0;
    int r = 0;
    int p = 0;
    int s = 0;
    unsigned seed;

    cout << "Chose either rock, paper, or scissors" << endl;
    cout << "Let r,p,and s represent rock,paper,and scissors respectively " << endl;   
    cin >> userChoice;
    cout << "You entered: " << userChoice << endl;
    cout << " " << endl;
    seed = time(0);
    srand(seed);
    randNumGenerated = rand() % 3;
    r == 0;
    p == 1;
    s == 2;
    

    if ((userChoice == 0 && randNumGenerated == 2) || (userChoice == 1 && randNumGenerated == 0) || (userChoice == 2 && randNumGenerated == 1))
    {
        cout << "You win!";
        
    }
    if ((userChoice == 0 && randNumGenerated == 1) || (userChoice == 1 && randNumGenerated == 2) || (userChoice == 2 && randNumGenerated == 0))
    {
        cout << "You lose!";
    }
    if ((userChoice == 0 && randNumGenerated == 0) || (userChoice == 1 && randNumGenerated == 1) || (userChoice == 2 && randNumGenerated == 2))
    {
        cout << "It's a draw!";
    }

    

    return 0;
}

这三行没有作用(字面上看,编译器应该警告您这一点):

r == 0;
p == 1;
s == 2;

您可能正在寻找这样的内容:

int userNum = -1;
switch (userChoice) {
    case 'r':
        userNum = 0;
        break;
    case 'p':
        userNum = 1;
        break;
    case 's':
        userNum = 2;
        break;
}

但是,为什么要使用整数呢?如果您使用字符表示,则if语句将更容易阅读:

char randomChosen = "rps"[randNumGenerated];
if ((userChoice == 'r' && randomChosen == 's') || ...) {
     std::cout >> "You win!n";
}

只要看一下这个,我就知道这是石头对剪刀。在基于数字的代码中,我必须回头查看转换表。