C ++如何刷新标准输入
C++ how to flush stdin
我有一个客户端处于接收模式并等待接收一些数据的程序;虽然如果用户在终端上写入程序被“阻止”,当程序从接收返回时我有一个 std::getline()
必须从标准输入读取但它读取用户在程序时给出的输入被屏蔽反而让我有机会做 std::cin
.
当程序在接收数据时被阻止时,如何刷新用户提供的所有输入?
这是伪代码:
{
...
int ret = receive(socket,buffer,0);
//During the receive the program will be blocked on the receive till it will be completed
//If the user type something in the stdin before the receive above it's completede when the getline it's executed it catch the bad input given by the user when the receive is processing
getline(cin, buffer);
...
}
您需要的是所谓的 Reactor。有一个设计模式。您想等待来自 2 个或更多来源的事件。
要解决此问题,您可以使用许多现有函数之一,例如 select
或 poll
或 epoll
。
使用此函数,您可以在您的操作系统的某个句柄(如套接字、文件句柄或 cin(在这个意义上只不过是句柄))上注册所需的事件。
只要您指定的事件在专用句柄上发生,函数就会 return 并指示发生的位置。然后你可以决定要做什么。
这些函数还有超时的版本。
因此,您将“阻塞”从 2 个函数 receive
或 getline
转移到一个函数,例如 epoll
.
如果您根本不想阻塞,而是想要异步处理,那么您可以使用带有完成处理程序的 Proactor 模式。这主要用于高速服务器应用程序。
但如今您也可以使用 std::async
和便宜的 future
轻松使用多线程函数
这应该可以解决您的问题。
我有一个客户端处于接收模式并等待接收一些数据的程序;虽然如果用户在终端上写入程序被“阻止”,当程序从接收返回时我有一个 std::getline()
必须从标准输入读取但它读取用户在程序时给出的输入被屏蔽反而让我有机会做 std::cin
.
当程序在接收数据时被阻止时,如何刷新用户提供的所有输入?
这是伪代码:
{
...
int ret = receive(socket,buffer,0);
//During the receive the program will be blocked on the receive till it will be completed
//If the user type something in the stdin before the receive above it's completede when the getline it's executed it catch the bad input given by the user when the receive is processing
getline(cin, buffer);
...
}
您需要的是所谓的 Reactor。有一个设计模式。您想等待来自 2 个或更多来源的事件。
要解决此问题,您可以使用许多现有函数之一,例如 select
或 poll
或 epoll
。
使用此函数,您可以在您的操作系统的某个句柄(如套接字、文件句柄或 cin(在这个意义上只不过是句柄))上注册所需的事件。
只要您指定的事件在专用句柄上发生,函数就会 return 并指示发生的位置。然后你可以决定要做什么。
这些函数还有超时的版本。
因此,您将“阻塞”从 2 个函数 receive
或 getline
转移到一个函数,例如 epoll
.
如果您根本不想阻塞,而是想要异步处理,那么您可以使用带有完成处理程序的 Proactor 模式。这主要用于高速服务器应用程序。
但如今您也可以使用 std::async
和便宜的 future
这应该可以解决您的问题。