hailey mcfarlin
hailey mcfarlin

Reputation: 31

Tokenizing a string C

Hello I am having trouble with a function that receives a string from a client in the format "number op number" ,op being a (+,-.*,/), then returns an answer to the client. I need help splitting the string into two num variables and one op variable.

Here is the function in question.

void func(int sockfd)
{
    char buff[MAX];
    int n, i, size, j;
    while (1) {
        bzero(buff, MAX);
        // read the message from client and copy it in buffer
        read(sockfd, buff, sizeof(buff));

        long int num1, num2, op;
        char temp[256];
        strcpy(temp, buff);
        sscanf(buff, "%s %s %s", num1, op, num2);

        // print buffer which contains the client contents
        printf("From client: %ld | | %ld", num1, num2);

Upvotes: 2

Views: 49

Answers (1)

Barmar
Barmar

Reputation: 780974

The correct format for reading a long int is %ld, %s is for strings.

You need & before any variables being read into with scanf() except for strings (since arrays automatically decay to pointers when used as function arguments).

op should be char rather than long int, and you should use %c format to read it.

You should limit the size of read() to sizeof buff - 1 so there will always be a null byte after the message that was read.

There's no need for the temp variable, you can just scan from buff.

You need to check the return value of read() to tell if the connection has been closed.

void func(int sockfd)
{
    char buff[MAX];
    int n, i, size, j;
    while (1) {
        bzero(buff, MAX);
        // read the message from client and copy it in buffer
        int n = read(sockfd, buff, sizeof(buff));
        if (n == 0) { // EOF
            break;
        } else if (n < 0) {
            perror("read");
            break;
        }

        long int num1, num2;
        char op;
        sscanf(temp, "%ld %c %ld", &num1, &op, &num2);

        // print buffer which contains the client contents
        printf("From client: %ld | %c | %ld\n", num1, op, num2);
    }
}

Upvotes: 4

Related Questions