Search code examples
c++boostasio

Boost asio read from stdin asynchronously


I want to read from standard input (in terms of c++, std::cin) with boost asio function async_read(). The following code does not compile and gives me a very long error message due to instantiation error. Can someone answer, how do I read from stdin asynchronously using this function?

char buf[64];

boost::asio::async_read(std::cin, boost::asio::buffer(buf),
                          [](const boost::system::error_code &ec, std::size_t size){});

Edit: I know there is a similar question already asked here Using boost::asio::async_read with stdin?, however it is not clear to me in which way the marked answer relates to the question


Solution

  • You have to use posix::stream_descriptor

    For example:

    using namespace boost::asio;
    io_context ioc;        
    posix::stream_descriptor input_stream(ioc, STDIN_FILENO);
    // assume that you already defined your read_handler ...
    async_read(input_stream, buffer(buf), read_handler);
    ioc.run();
    

    Note that you shouldn't mix the above code with std::cin

    For more information please see here.