有没有办法隐藏cout(C ++)中的变量?

时间:2015-05-31 01:06:29

标签: c++ variables

我在cout函数中找出如何隐藏特定变量(如果可能的话)的问题。基本上我需要做一个数字猜测游戏,这很容易,除了我们的老师希望我们像随机数学方程式那样做。哪个......老实说还是相当容易,除了我们必须这样做的方法是程序必须随机创建问题,然后随机选择3个数字中的一个来显示,用户必须猜测其他两个缺失的数字。例如,如果程序选择20 + 32 = 52,则可能显示__ + 32 = __。

我已经走了那么远但是我无法弄清楚如何制作它所以它显示如此但仍然允许我把这样的行

    cout << num1 //Hidden << " + " << num2 << " = " << num3 //Hidden

但就像我说的那样,我甚至不知道如果不可能,那么我可能不得不重写整个程序。这就是我到目前为止所做的:

int main()
{
    int num1, num2, num3, random1, guess1, guess2;
    string play = "";

    cout << "Would you like to run the number guessing program? (enter yes or no): ";
    getline(cin, play);
    for (int i = 0; i < play.length(); i++)
    {
        play[i] = tolower(play[i]);
    }

    //Random seed
    srand(time(0));

    while (play == "yes")
    {
        //Generate random numbers and num3
        num1 = 1 + rand() % 50 + 1;
        num2 = 1 + rand() % 50 + 1;
        num3 = num1 + num2;
        int pickRandom[3] = { num1, num2, num3 };

        //Display random elements
        random1 = pickRandom[rand() % 3];

        if (random1 == num1){
            cout << "\nYour randomly generated number problem: " << num1 << " + " << "__" << " = " << "__" << endl;
        }
        if (random1 == num2){
            cout << "\nYour randomly generated number problem: " << "__" << " + " << num2 << " = " << "__" << endl;
        }
        if (random1 == num3){
            cout << "\nYour randomly generated number problem: " << "__" << " + " << "__" << " = " << num3 << endl;
        }
        //Get Guesses
        cout << "\nBased off of this information please make an educated guess as to what the two missing numbers are.";
        cout << "\n\nGuess for number 1 (between 1 and 100): ";
        cin >> guess1;
        while ((guess1 > 100) || (guess1 < 0))
        {
            cout << "\nSorry you need to enter an integer between 1 and 100" << endl;
            cout << "\nGuess for number 1 (between 1 and 100): ";
            cin >> guess1;
        }
        cout << "\n\nGuess for number 2 (between 1 and 100): ";
        cin >> guess2;
        while ((guess2 > 100) || (guess2 < 0))
        {
            cout << "\nSorry you need to enter an integer between 1 and 100" << endl;
            cout << "\nGuess for number 2 (between 1 and 100: ";
            cin >> guess2;
        }
        if (guess1 == )
    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

我认为你不能隐藏cout中的变量。但您可以使用变量而不是硬编码&#34; __&#34;。

例如,您可以简单地写一下:

  if(guessed_var1_correctly)
      var1 = num1
  else
      var1 = "__"

  if(guessed_var2_correctly)
      var2 = num2
  else
      var2 = "__"

  if(guessed_var3_correctly)
      var3 = num3
  else
      var3 = "__"

  cout << "\nYour randomly generated number problem: " << var1 << " + " << var2 << " = " << var3" << endl;

其中var1,var2,var3是输出变量。如果玩家猜对了,它会显示实际值num1,num2或num3。如果没有,它只会显示&#34; __&#34;。