can i make my own working functions

Apr 19, 2019 at 9:49pm
closed account (N8MNAqkS)
is there a way I can make my own std::cout function that actually prints something to the console window. I just learned how to use namespaces and I got the idea to just make my own std::cout but with a different namespace. I know it would be pointless but FOR SCIENCE!!!
Last edited on Apr 19, 2019 at 9:50pm
Apr 20, 2019 at 4:48am
yes, you can. if you want to do it way down deep you will need to call the operating system itself -- possibly using assembly language inside your C++.
but say you wanted to use prinf to make a new cout … you can do this. It may be possible to open the console as if it were a FILE* or even a c++ object, not sure. Stdin/stdout itself really is a C FILE*.
Last edited on Apr 20, 2019 at 4:49am
Apr 20, 2019 at 5:53am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <iomanip>
#include <ctime>

namespace my_own
{
    struct ostream_proxy : std::ostream
    {
        explicit ostream_proxy( std::ostream& stm ) : std::ostream( stm.rdbuf() ), old_stm(stm) {}
        ~ostream_proxy() { old_stm.rdbuf( rdbuf() ) ; }

        private: std::ostream& old_stm ;
    };

    static ostream_proxy cout{std::cout} ;

    using std::setw ;
    using std::setfill ;
    using std::put_time ;
    using std::endl ;
}

int main()
{
    const auto now = std::time(nullptr);
    const auto calendar_time = *std::localtime( std::addressof(now) ) ;

    my_own::cout << "hello world! " << my_own::setw(12) << my_own::setfill('0') << 12345
                 << " [" << my_own::put_time( std::addressof(calendar_time), "%F %T %Z]" ) << my_own::endl ;

}

http://coliru.stacked-crooked.com/a/f67ca024a482c313
https://rextester.com/XQPS66958
Topic archived. No new replies allowed.