简体   繁体   中英

C++ clear input buffer (no newline in the end)

I have a server that handles multiple clients with select-accept.

The clients can connect and send messages to server, the server can send messages to any client anytime. The clients use accept to check stdin and socket for messages.

Let's say two clients connected at the same time. First client starts typing message to server, meanwhile (in result of the second client's message) the server sends message to the first client. The first client immediately displays the servers message after a newline, interrupting the console input. Then the first client retypes the message and presses enter, but the problem is the unfinished part of the message (which entered before server message arrived) also being sent.

Possible results on console:

./client
Server says: Hi Tom! Use commands get, set, exit.
Tom> exi
Server says: Your friend<Peter> arrived.
Tom> exit

In the example above the client(Tom) tries to send exit.

./server
Waiting connections...
Tom arrived.
Peter arrived. Notifying friends: Tom...
Tom -> exiexit

The server gets exiexit instead of exit .

The question is how to clean the input? I've tried the followings and combinations:

std::cin.ignore(INT_MAX);
std::cin.ignore(INT_MAX, '\n');
while ((ch = getchar()) != '\n' && ch != EOF);
scanf("%c%*[^\n]%*c", &c);
std::getline(std::cin, buffer);
gets(buffer);
std::cin.sync();
std::cin.seekg(0, std::cin.end);

But the main problem either the operation blocks so I have to press enter, or it doen't clean the input, or both.

This is something that is not easily done in portable C/C++. What you need to do is interacting more strongly with the terminal so you can precisely control what happens.

On Linux, for example, there is the ncurses library that helps you moving the cursor around in the terminal and reading in character by character without line buffering etc. This would allow you to reprint partial input lines on stdout so the user can see what is actually going on. The low-level API for this is termios (see man 3 termios ).

On Windows there are similar possibilities but a very different interface, the console familiy of functions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM