ascii - int to character

Recommended Posts

cherryhouse    100
Could I be pointed out the problem with this code? I've tested the network to make sure the correct integers are being sent over the network, and they are, so why isn't the client doing its job of converting the integer to a character?
while (bytes = recv(sockfd,
recvbuf,
4,
0) == -1)
// Output error message if error occurs
{ Msges.ErrorMsg("Error while receiving.");
return exit(1); }

switch(atoi(recvbuf))
{
case 43 : cout << '+'; break;

default: break;
}



Share on other sites
Evil Steve    2017
atoi() takes in a string, and gives you an int, so recvbuff will have to contain a NULL terminated string. If you have an int, you can do this:
while (bytes = recv(sockfd,                     recvbuf,                     4,                     0) == -1)                     // Output error message if error occurs                     { Msges.ErrorMsg("Error while receiving.");                       return exit(1); }    switch(*(int*)recvbuf)    {        case 43 : cout << '+'; break;        default: break;    }

Share on other sites
jflanglois    1020
You are going to have to tell us how you are sending this integer. Using atoi may not be the correct solution.

Apart from that, perhaps the string you are feeding into atoi is not null terminated.

jfl.

Share on other sites
cherryhouse    100
The constructor does necessary "nullifying" to char recvbuf[5];

Client::Client(){ for(int i = 0; i <= 5; i++) recvbuf[i] = '\0'; }

The sending looks like this

/*move the ascii decimal value into a string to send over the network */            itoa(i, newb, 10);             client.SendMessage(newb);void Client::SendMessage(char* set_msg){    // sockfd: Socket in which data is sent through    // buf.c_str(): String in which data is sent from    // bufsize: Amount of bytes to send (value == size of buf)    if (bytes = send(sockfd,                     set_msg,                     5, //perhaps i'm sending too many bytes?                     0) == -1)                     // If error occurs, exit program                     { return exit(1); }}

Share on other sites
Evil Steve    2017
You're sending 5 bytes, but recieving 4. That's not going to work properly.

Is there a reason you're converting to text to send over the network? It's much more efficient to send them as raw data, just make sure you use htonl and ntohl to convert the values if you're supporing multiple platforms / OSs.

Share on other sites
cherryhouse    100
well, Apparently, when I receive the string it ends up looking like so:

" 6 5 "

I don't even know how I can pick apart this string so that it's simply "65", so I think I'll just leave this alone for now.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account