> int sr = recv(acc, buffer, sizeof(buffer), 0);
1. recv doesn't store a \0 on the end to make it a proper string
2. You need to leave room to store the \0 yourself
3. You need to code for the possibility that recv() doesn't receive the whole message in one go (if this is a TCP connection)
int sr = recv(acc, buffer, sizeof(buffer)-1, 0);
if ( sr > 0 ) {
buffer[sr] = '\0'; /* make it a string */
/* now you can do str... operations on buff */
}
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
> The output of sr is 1, which is not the size of the buffer
Who said it would be?
The size you pass is "don't go past this many characters", not "please hang around until you fill the buffer".
You got 1 character, so copy it to somewhere else, and call recv() again.
Keep calling it until you have all your data.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
> But, I didn't need to add a null pointer to the end of the string. It works anyways.
1. It's a NUL char, not a NULL pointer.
2. Yes, you do need to add it, otherwise you're relying on the buffer being initialised (which it isn't).
On the other hand, you could be sending the \0 (either by accident or by design).
Wanna see?
Try
memset( buffer, 0xff, sizeof(buffer); /* very specific non-zero fill */
sr = recv(acc, buffer, sizeof(buffer)-1, 0);
cout << "sr = " << sr << "\n";
buffStr = buffer;
Now see whether buffStr is correct or not?
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953