문제

for like few hours now, I am trying to figure out how to read characters from cin before pressing ENTER (by using threads). I know about conio.h library but I prefer not to use it.

I wrote simple program that gets data from user and saves it in 'msg' string. Program has child thread that clears the console every second. What I want to do is:

  1. User puts some data but doesn't press ENTER so it's not saved in 'msg' variable.
  2. Console clears
  3. send to cout the characters user typed, so he won't even notice that console was cleared.

PS. Sorry for my english, here's the program:

#include<iostream>
#include<string>
#include<winsock2.h>
#include<process.h> 
#include<windows.h>
using namespace std;


void __cdecl ThreadProc( void * Args )
{

    while( true ){
        system("cls");
        cout << "Input: ";
        /*
        char c;
        while((c=cin.peek()) != '\n')
            cin.get(c);
        cout << c;
        */
        Sleep(1000);
    }
    _endthread();
}


int main(){
    HANDLE hThread =( HANDLE ) _beginthread( ThreadProc, 0, NULL );

    while (true){
        string msg;
        getline(cin,msg);
        cout << "MSG:" << msg << endl;
        cin.clear();
        fflush(stdin);
    }
    return 0;
}

EDIT:

Key-logger? Nah, I am doing console network chat. Currently server and client can chat with each-other. When new message is received or sent, it is saved in "vector<\string> chat" and console is refreshed below code:

void show_chat(){
    system("cls");
    for(unsigned int i =0;i<chat.size();i++){
        cout << "[" << date[i].tm_hour << ":" << date[i].tm_min << ":" << date[i].tm_sec << "] " << chat[i] << endl;
    }
    cout << "Input: ";
}

So there is a problem if new message is received while user is writing his own message. Part of the message written before message system("cls") is lost on the screen.

도움이 되었습니까?

해결책

To do what you want, you will need to incorporate a message queue and update method.

Can you do it the way you have presented? Sure, but it's going to be a major pain and there's no way to do this with cin.

Simply have a message queue on both sides, a current status of each client(able_to_receive_messages, unable, etc), and an update method that is called by each client is run after the user is once again able to receive messages.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top