How can I store token values in an array?

Asked

Viewed 126 times

-1

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <assert.h>

typedef struct{
    int id;
    char nome[20];
    char telefone[9];
}tipoCliente;

int main(){
    int n,q,i,j,cont;

    printf("Qtds:\n");
    scanf("%d %d",&n,&q);

    tipoCliente cliente[n];

    for(i = 0; i < n; i++){
        scanf("%d %s %s",&cliente[i].id,&cliente[i].nome,&cliente[i].telefone);
    }

    printf("\n");
    for(i = 0; i < n; i++){
        printf("%d %s %s\n",cliente[i].id,cliente[i].nome,cliente[i].telefone);
    }

    for(i = 0; i < n; i++){
        j = atoi(cliente[i].telefone);
        cont = strlen(cliente[i].telefone);

        char* token = strtok(cliente[i].telefone,"-");

        while(token != NULL){
            printf("%s\n",token);
            token = strtok(NULL,"-");
        }

        printf("\n");
    }

    return 0;
}

  • What do you mean? Give an example to understand what is supposed to be done...

1 answer

1


Do you agree that token is a variable of the type char *? To store this tipo de dado simply state a vector of char *, note that hence this pointer vector which you will declare will serve to store pointers to the beginning of tokens, and not as storage for their copy.

If you strictly need the copy, you can use strcpy() together with a two-dimensional vector to store its values, as strcpy() ends copying a string when it finds a 0 (ASCII code, not to be confused with the character '0'). For example:

char s[100] = "908-123-3332";

The first call from strtok() will return the address which has a value different from the characters present in the bounding argument, from the function strtok(), that in my example is '9' in this example the address 6, on the second call will be the address 10, in the third 15 and the last NULL, and the variable s[100] will equal

+-------------------------------------------------------------------------------
+| '9' | '0' | '8' |  0  | '1' | '2' | '3' |  0  | '3' | '3' | '3' | '2' | 0 | ...
+   6  -  7  -  8  -  9  - 10  -  11 -  12 - 13  -  14 -  15 -  16 -  17 - 18 - ...
+-------------------------------------------------------------------------------

discounting the vertical bars that were used only as to divide the vector into each of its positions (addresses), which were placed on the bottom line.

For example, if you use strcpy(destino, 6) where 6 is the address, the variable destino will be

'9' | '0' | '8' | 0 | ...

If it were strcpy(destino, 11) the string destino would be

'2' | '3' | 0 | ...

Based in this post soen.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.