This code is embedded in a “chat room” program using sockets. It is reading from the client (myFD) and successfully appending a username to the front.
However, I have a problem writing extra characters in the write buffer. What was sent last time is still stored and also sending.
For example, the first time I’d send (and write correctly)
UN: Hello.
But on the second try, when I’d write, say, “NOT”, the message sent would be:
UN: NOTlo
The cout statement correctly “cout’s” without the “lo” at the end, but the clients receive the “lo” at the end. Am I overlooking something simple?
Code Below:
while ( (amount_read = read(myFD, buffer, 1024)) > 0)
{
total = 0;
strcpy(second, "");
strcpy(second, username);
total += unLength;
strcat(second, ": ");
total += 2;
strcat(second, buffer);//, amount_read);
total += amount_read;
cout << second << endl;
write(myFD, second, total);
}
Thanks!
Your string is not null terminated that’s why you print old string. You can fix it adding
\0at the end of stringbuffer[amount_read]=0or just clear whole string before next iteration.To clear buffer you can use
memset (buffer,'\0', 1024). Maybe it’s not fastest way but prevent storing rubbish or data that shouldn’t be hosted longer than it’s necessary.