1//
2// stdin_line_reader.cpp
3// ~~~~~~~~~~~~~~~~~~~~~
4//
5// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
6//
7// Distributed under the Boost Software License, Version 1.0. (See accompanying
8// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9//
10
11#include "stdin_line_reader.hpp"
12#include <boost/asio/deferred.hpp>
13#include <boost/asio/read_until.hpp>
14#include <iostream>
15
16stdin_line_reader::stdin_line_reader(boost::asio::any_io_executor ex)
17 : stdin_(ex, ::dup(STDIN_FILENO))
18{
19}
20
21void stdin_line_reader::async_read_line_impl(std::string prompt,
22 boost::asio::any_completion_handler<void(boost::system::error_code, std::string)> handler)
23{
24 std::cout << prompt;
25 std::cout.flush();
26
27 boost::asio::async_read_until(s&: stdin_, buffers: boost::asio::dynamic_buffer(data&: buffer_), delim: '\n',
28 token: boost::asio::deferred(
29 [this](boost::system::error_code ec, std::size_t n)
30 {
31 if (!ec)
32 {
33 std::string result = buffer_.substr(pos: 0, n: n);
34 buffer_.erase(pos: 0, n: n);
35 return boost::asio::deferred.values(args&: ec, args: std::move(result));
36 }
37 else
38 {
39 return boost::asio::deferred.values(args&: ec, args: std::string{});
40 }
41 }
42 )
43 )(std::move(handler));
44}
45

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of boost/libs/asio/example/cpp20/type_erasure/stdin_line_reader.cpp