简体   繁体   中英

Problems Converting Char to Int in C++

I'm trying to make this rock, paper, scissors game work but I am having trouble getting past the "You have entered line" as it terminates after that.

My professor said my problem is that userChoice is of type char when randNumGenerated is of type int. I tried to convert my r,p,and s values by using the below: char r = 'a'; int a = r;

But got a "redefinition:different basic types" error from the compiler. I'm not sure what to do, as redefining the variables to int was my intention. Am I thinking of this all wrong? Any help would be greatly appreciated !

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;

}

These three lines have no effect (literally, and the compiler should be warning you about this):

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

You are probably looking for something like:

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

But then, why are you even using integers at all? Your if statements would be easier to read if you used the character representations:

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

Just by looking at this one, I can see it is Rock vs Scissor. In your number-based code, I'd have to look back at the conversion table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM