简体   繁体   English

将 char[] 与逗号分开

[英]separate char[] from comma

I have a program that need's to communicate client/server with socket's.我有一个程序需要与套接字通信客户端/服务器。

I need to receive the data at real time and work with the data.我需要实时接收数据并使用数据。

Atm I'm receiving the data all in a char array[] but the data is separated by comma. Atm 我在 char array[] 中接收所有数据,但数据用逗号分隔。 I'm trying to find a way to separate the data.我试图找到一种方法来分离数据。

I've tried the strtok , separate by comma but stop the connection with server, so I got only 1 piece of data.我试过strtok ,用逗号分隔,但停止与服务器的连接,所以我只有一条数据。

My code is this one:我的代码是这个:

#include<stdio.h> //printf
#include<string.h>    //strlen
#include<sys/socket.h>    //socket
#include<arpa/inet.h> //inet_addr
#include<unistd.h>
#include <cstring>

int main(int argc , char *argv[]) 
{
    int sock;
    struct sockaddr_in server;
    char message[1000] , server_reply[2500];
    char* chars_array = strtok(server_reply, ",");
    //Create socket
    sock = socket(AF_INET , SOCK_STREAM , 0);
    if (sock == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons( 51717 );

    //Connect to remote server
    if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        perror("connect failed. Error");
        return 1;
    }

    puts("Connected\n");

//keep communicating with server
    while(1)
    {
       /* printf("Enter message : ");
        scanf("%s" , message);
        //Send some data
        if( send(sock , message , strlen(message) , 0) < 0)
        {
            puts("Send failed");
            return 1;1
        }*/
        //Receive a reply from the server
        if( recv(sock , server_reply , 2500 , 0) < 0)
        {
            puts("recv failed");
            break;
        }
        puts("Server reply :");
        //puts(server_reply);
        //MessageBox(NULL, subchar_array, NULL, NULL);
        chars_array = strtok(NULL, ",");
        puts (chars_array);
    }
    close(sock);
    return 0;
}

The first call of strtok will only return the first token of the string you are seperating.第一次调用strtok只会返回您要分隔的字符串的第一个标记。 To get the other tokens from the same source string, simply call strok(NULL,',');要从同一源字符串中获取其他标记,只需调用strok(NULL,','); again until you are through with all of them.再次,直到你完成所有这些。 If there are no tokens left, this call will return NULL instead, so be careful.如果没有留下任何标记,则此调用将返回NULL ,所以要小心。

Additional, take notice that strtok actually modifies the string that you pass to it.另外,请注意 strtok 实际上修改了您传递给它的字符串。 If you don't want that, make a copy for tokenizing first using strcpy .如果您不希望这样,请先使用strcpy制作一个用于标记化的副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM