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:
- User puts some data but doesn't press ENTER so it's not saved in 'msg' variable.
- Console clears
- 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.