简体   繁体   中英

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. 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.

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. To get the other tokens from the same source string, simply call 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.

Additional, take notice that strtok actually modifies the string that you pass to it. If you don't want that, make a copy for tokenizing first using strcpy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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