Retrieving string out of token and put in array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Someone21
    New Member
    • Dec 2009
    • 1

    Retrieving string out of token and put in array

    Hi all,

    I am currently trying to retrieve a string from a textfile, separate that and put it in an array.

    I stumbled on the problem that *token is a pointer, and not the string. However when i printf("%s", token) it prints out the word that it points to. Could anyone explain how to fix this problem?

    Words.txt:

    dog|cat|hamster

    The code:
    char c[50000]; /* declare a char array */
    int n;
    FILE *file; /* declare a FILE pointer */
    file = fopen("words.tx t", "r");
    n = fread(c, 1, 50000, file);
    c[n] = '\0';

    /* Separating the contents, divided by | */

    char *token = strtok(c, "|");
    char words[50000];
    int f = 0;
    while(token != NULL)
    {
    printf("[%s]\n", token);
    /* Here the error is caused: invalid conversion from char* to char */
    words[f] = token;
    token = strtok(NULL, "|");
    f++;
    }
    fclose(file);
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Code:
    char *token = strtok(c, "|");
    *token is not a pointer. The code above says that *token is a char.

    It is token that is a pointer of char.

    When C functions see a char*, they usually assume a null-termninated string. So printf displays the string atthe address in token.

    This code:

    Code:
    char words[50000];
    int f = 0;
    while(token != NULL)
    {
    printf("[%s]\n", token);
    /* Here the error is caused: invalid conversion from char* to char */
    words[f] = token;

    attempts to assign a pointer to char (token) to a char. Hence, the invalid conversion from char* to char.

    I expect you want to copy the string pointed at by token to the words array.

    If so, you need a) an array of char* rather than char, b) you need to allocate memory for words[f] and finally strcpy from token to words[f] to place the string in the array.

    Comment

    Working...