字符串和int连接

时间:2014-03-05 05:13:39

标签: c++ string client-server fgets

我必须将fgets的输出连接到intclientid),并将其存储在char[1024]缓冲区中。

这是我的代码:

clientid = rand() % 256;



while(1)
{
    cout<<"Client: Enter Data for Client=";

    fgets(buffer,MAXSIZE-1,stdin);

    if((send(sockfd,buffer,strlen(buffer),0))==-1)
    {
        cout<<"Failure Sending Message";
        close(sockfd);
        exit(1);
    }
    else
    {
        cout<<"Client:Message being sent:"<<buffer;
        num=recv(sockfd,buffer,sizeof(buffer),0);
        if(num<=0)
        {
            cout<<"either connection close or Error";
            break;
        }
        buffer[num]='\0';
        cout<<"Client:message received from Server:"<<buffer<<endl;
    }
}

close(sockfd);
return 0;

如何从服务器端的消息中提取clientid

2 个答案:

答案 0 :(得分:1)

您可以将其添加到缓冲区本身的开头。例如,如果你的clientid是123,那么你可以发送“123:Message”,其中“:”可以作为分隔符。这意味着你应该在缓冲区中提前读取那么多数字,而不是从头开始。

snprintf (buffer, sizeof(buffer), "%d:", clientid); // Add the clientid at the beginning before reading 
fgets(buffer + strlen (buffer),MAXSIZE-1,stdin);// Move by the len of buffer which contains clientid

答案 1 :(得分:1)

您可以使用strcat()方法将消息与clientId连接,如下所示:

 strcat(buffer, clientid);

在服务器端,您可以通过从缓冲区中选择子字符串来识别clientid,如下所示:

  std::string str=buffer;

  std::string str2 = str.substr (messagelength,lastindex);