Rock Paper剪刀的整数到字符转换

时间:2011-12-13 09:35:47

标签: c++ char int

Hello是否有一种将int转换回char的不同方法,请参阅有关代码一半的注释。我正在考虑使用开关或if语句,但我无法弄清楚应用它。我用char RPS [] = {'?','R','P','S'};

  #include <iostream>
    using namespace std; 
    #include <ctime>
    #include <cstdlib>

    //human choice function
    int hchoice()
    {
        char entry;
        int usrchoice = 0;

        while (1)    
         {
         cout <<"Choose R for Rock P for Paper, S for Sissors or Q for quit ";
         cin >> entry;
         cin.ignore(1000, 10);
         switch (toupper(entry)){
         case 'R':
           usrchoice = 1;
           break;
         case 'P':
           usrchoice = 2;
           break; 
         case 'S': 
           usrchoice = 3;
           break; 
         case 'Q':
           usrchoice = -1; 
           break; 
         } 
         if (usrchoice != 0)break;

         cout << "Invalid Entry" <<endl;


        }
    return usrchoice;
    }
    //Computer choice function
    int compchoice()
    {
          return (1 + rand() % 3);
    }
    void printresults(int computer, int human)
    {
    //Number to char converter? Can i use a switch here?
    char RPS[] = {'?', 'R', 'P', 'S'};

     cout << "Computer:" << RPS[computer];
     cout << ", Human:" << RPS[human];
     cout << ",  ";

    if (computer == human){
      cout <<"tie";
    }
    else if ( ( human==1 && computer == 2) || (human == 2 && computer == 3) || (human == 3 && computer == 1)){
    cout << "computer wins!";
    }
    else {
    cout <<"Human Wins!";
    }
    cout << endl;


    }


    int main()
    {
     // initialize the computer's random number generator
    srand(time(0)); rand();
      // declare variables
     int human = 0, computer = 0;

      // start loop
    while (1)  
    {
        // determine computer's choice
        computer = compchoice();
        // prompt for, and read, the human's choice
        human = hchoice();
        // if human wants to quit, break out of loop
           if (human == -1) break;
        // print results
         printresults(computer, human);
        cout << endl;
      // end loop
    }//while
      // end program
     return 0;
    }

1 个答案:

答案 0 :(得分:1)

可以在那里使用switch或一系列if语句。但是,你现在拥有的是迄今为止最简洁的 - 我认为 - 最容易阅读。

我建议的另一个更普遍的事情是使用符号常量(例如enum)而不是硬编码的数字123你的代码中有好几个地方。