是否有一种方法来隐藏变量在cout (c++)

Is there a way to hide variables in cout (C++)?

本文关键字:变量 隐藏 cout c++ 一种 是否 方法      更新时间:2023-10-16

我在计算如何在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 << "nnGuess 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 << "nnGuess 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;
}

我不认为你可以在cout中隐藏变量。但是你可以使用一个变量而不是硬编码"__"。

例如,您可以简单地这样写:

  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。如果不是,它将简单地显示"__"。