Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : cin while cout [closed]

Tags:

c++

Well, I'm writing a Chat in C++ to be used in linux terminal. I want to receive messages even while I'm typing. basically, a non-blocking cin. I managed to get this work by creating a thread. BUT the problem is that incoming messages and my typing are getting merged together.

Is there any way to separate cin line from other lines coming from cout?

Sorry for my English.

like image 534
Ikbel Avatar asked Jan 09 '23 05:01

Ikbel


2 Answers

Is there any way to separate cin line from other lines coming from cout?

Yes, but it is a little tricky: you need to disable echo for the console, and print the characters typed in by end-user as he types.

When you detect an incoming message, you need to do these three things:

  • Clear out all characters on the line the end-user has entered so far
  • Print the incoming message
  • Print the characters entered so far on the next line.

The end result would look like this:

Friend: How are you?                        <== This is your friend's prior message
You: > I am fi                              <== This is the text you've entered so far

When the next message comes in before you finished typing, you re-arrange the last lines as follows:

Friend: How are you?                        <== This is your friend's prior message
Friend: Are you coming to school tomorrow?  <== This is the new line that came in as the user was typing
You: > I am fi                              <== This is the text you've entered so far, re-printed again
like image 130
Sergey Kalinichenko Avatar answered Jan 18 '23 02:01

Sergey Kalinichenko


My idea is to store incomplete client's message (that has not been sent yet) in a variable and when program receives incoming messages, it should erase client's message with backspaces, write incoming message to cout and then rewrite client's incomplete message.

I have not checked it though.

like image 26
Savenkov Alexey Avatar answered Jan 18 '23 03:01

Savenkov Alexey