How to output a string from an int?

Hello! I was finishing up an assignment for my computer science class but I've run into a small problem. Everything in my program works as it should, but when the results are displayed, they are shown as ints. I was wondering if there was a way to display a string instead of a number. For example:
"1" would display as "Rock"
"2" would display as "Paper"
"3" would display as "Scissors"
"4" would display as "Lizard"
"5" would display as "Spock"

Here is my function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int displayChoice (int computer, int user, int result)
{
    if (result == 0)
    {
        cout << "DRAW\n" << "Your Choice: " << user << "\nComputer's Choice: " << computer << endl;
    }
    if (result == 1)
    {
        cout << "YOU WIN!\n" << "Your Choice: " << user << "\nComputer's Choice: " << computer << endl;
    }
    if (result == 2)
    {
        cout << "COMPUTER WINS!\n" << "Your Choice: " << user << "\nComputer's Choice: " << computer << endl;
    }

    return 0;
}


The variables user and computer are the integer values that I want to convert to a string to display a word. Thank you in advance!
closed account (49iURXSz)
One way to do it would be to call a function that does this for you:

Note: This is just a declaration.
 
void printChoice( int choice );


Inside, just switch on the choice:

1
2
3
4
5
6
7
8
9
switch(choice){
    case 0:
        std::cout << "Rock";
    case 1:
         std::cout << "Paper";
    case 2:
         std::cout << "Scissors";
    /* etc... */
}


So:

1
2
3
4
5
6
7
8
9
if (result == 0) {
        cout << "DRAW\n" << "Your Choice: ";
        printChoice( user );
        cout  << "\nComputer's Choice: ";
        printChoice( computer );
        endl;
}

/* And So On... */


Alternatively, if you want to keep the style you have:

cout << "DRAW\n" << "Your Choice: " << user << "\nComputer's Choice: " << computer << endl;

Just return the string instead:

1
2
3
4
5
6
7
string writeChoice( int choice ) {
    switch(choice) {
        case 0:
            return "Rock"
        /* etc... for case 1, case 2, */
    }
}


Then:


cout << "DRAW\n" << "Your Choice: " << writeChoice( user ) << "\nComputer's Choice: " << writeChoice( computer ) << endl;

You could make your code clearer by enumerating your choices, but that's up to you. See (http://stackoverflow.com/questions/12183008/how-to-use-enums-in-c) for details.
Last edited on
Thank you very much!
Topic archived. No new replies allowed.