1

I want to create a manipulator that delays between every character like if i write

delay wait = 40;
cout << wait << "Hello World!";

It should output 'H' then Sleep(40), 'e' then Sleep(40), 'l' then Sleep(40) and so on, i tried to write a class for this and here is my code:

class delay {

public:
    delay(const int& amount) {                        // getting the amount for Sleep(...)
        this->Amount = amount;
    }
    delay& delay::operator = (const int& amount) {    // same, but for operator=
        this->Amount = amount
        return *this;
    }

private:
    ostream& m_os;
    int Amount;
    friend ostream& operator << (ostream& os, delay& p) {    // i dont know if I even need this
        p.m_os = os;
        return os;
    }
    friend ostream& operator << (delay& p, const char* n) {  // here it should do output and delay
        int index = 0;
        while (n[index] != '\0) {
            p.m_os << n[index];    // output character
            index++;
            Sleep(p.Amount);       // wait
        }
    return p.m_os;
    }

};

I get errors when i try to use this code and i kinda think i have to start rewriting this from the beginning. I hope you have an idea how to realize this delay class because i tried everything i could and it doesnt work. Thank you for reading this, I hope that you can help me <3

Brogramer
  • 75
  • 8
  • Manipulator changes state of the stream, such delay has to be in a stream, so you will have to inherit and write your own stream implementation. – Slava Jul 31 '15 at 18:34
  • 1
    You should probably use a standard function like [`std:::this_thread::sleep_for`](http://en.cppreference.com/w/cpp/thread/sleep_for) rather than `Sleep()`. – πάντα ῥεῖ Jul 31 '15 at 18:37
  • First of all thank you for answering, so it has to be something like mystream os; int wait = 30; os << wait << "like this?"; am i right? :D – Brogramer Jul 31 '15 at 18:39
  • @Brogramer Also please provide a [MCVE](http://stackoverflow.com/help/mcve) to improve your question. _"I get errors when i try to use this code"_ is too vague for a valid question here! – πάντα ῥεῖ Jul 31 '15 at 18:45
  • Sorry about that but I think i dont need to add this anymore, because the code I wrote is totally useless as Slava already said i need to write a stream implementation so i have to start from the beginning :D – Brogramer Jul 31 '15 at 18:56

1 Answers1

0

cout << wait << "Hello World!"; is (cout << wait) << "Hello World!"; so your operator never gets invoked. Simple debugging would have shown this! You will need a proxy object, basically. Still, I don't think you should do this. You'll block the thread. Why not use a proper task scheduler to produce output on a schedule?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055