我必须将 fgets
的输出连接到 int
(clientid
),并将其存储在 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
?
最佳答案
您可以将其添加到缓冲区本身的开头。例如,如果您的 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
关于c++ - 字符串和整数连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22189142/