Using cout to print a statement only once in a function that is repeatedly called [closed]

StackOverflow https://stackoverflow.com/questions/20458795

  •  30-08-2022
  •  | 
  •  

Domanda

Is it possible to print a line of text using cout in windows, to the console only once inside a function that is repeatedly called or updated?

To give some scope, I have a keyboard input function that is called to check for key presses and when I press "C" my camera's values are updated and I print out confirmation to the console like this: cout << "\nView switched to 'Default View..." << endl;` but it prints it forever in a infinite loop.

This may sound like a simple question, but this is the first time I've come across and issue like this.

void keyboard()
{
   if (CAM_DEF) //switch to default view
   {
       cout << "\nView switched to 'Default View`..." << endl;
       Q_PRESSED = false;
       E_PRESSED = false;
   }
    ... //more key presses
}
È stato utile?

Soluzione

You could use a static local variable to guard against the print happening multiple times:

void function()
{
    static bool runOnce= true;

    if(runOnce)
    {
        cout << //print stuff
        runOnce = false;
    }
    ... do other stuff
}

OR a C++11 fancy pants answer using a lambda, which is shorter but arguably less readable:

using namespace std;

void function()
{
    static const auto runOnce = [] { cout << "Hello" << endl; return true;}();
}

int main()
{
    function();
    function();
    function();

    return 0;
}

Result:

Hello
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top