c++ - 石头剪刀布的整数到字符的转换

标签 c++ char int

你好,有没有不同的方法可以将 int 转换回 char,请参阅代码中途的注释。我在考虑使用 switch 或 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;
    }

最佳答案

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

我建议的更一般的事情是使用符号常量(例如 enum)而不是硬编码数字 123,您在代码中的多个位置。

关于c++ - 石头剪刀布的整数到字符的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8486957/

相关文章:

c++ - 在 C++ 中以这种方式创建字符串数组是否正确?

c# - SetupDiEnumDriverInfo 始终返回错误 259(没有更多可用数据)

c++ - 信号 : Segmentation fault (11) when using Openmpi

c++ - 影响格雷厄姆寻找凸包算法的未知错误

c# - Int32.TryParse() 失败时返回零 - 成功还是失败?

c++ - 我的逻辑让我失望(C++、nslookup、字符比较)

c++ - 了解字符数组初始化和数据存储

c - 使用 printf 打印字符时出现类型错误

c++ - 将单个字符转换为整数

计算sinh的泰勒级数