How to get first and last word from lines in C?

Viewed 394

I have a problem with code. I want to take first and last words from each lines from txt file. I wrote this code for now:

void StartEnd(char * word)
{
    FILE* fp;
    fp = fopen("linie.txt", "r");
    if (fp == NULL) {
      printf("! ");
      return;
    }
    char store[MAX_LINE];
    
    while (fgets(store, MAX_LINE - 1, fp)){
    char * FirstWord = strtok(store," ");
    char * LastWord;  
    char * token = strtok (store," ");
    while (token != NULL){
    LastWord = token;
    token = strtok (NULL," ");
}
    printf("%s\n",LastWord);
    }
    
    fclose(fp);
 
}

It is working for last word but only if i dont use FirstWord with strtok and i dont know why :(. I would be grateful for any answer. Thanks!

1 Answers

On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of the last token as the new starting location for scanning.

On subsequent calls to strtok, you are supposed to pass a NULL pointer. Doing that makes the function work properly:

void StartEnd(char * word)
{
    FILE* fp;
    fp = fopen("linie.txt", "r");
    if (fp == NULL) {
      printf("! ");
      return;
    }
    char store[MAX_LINE];

    while (fgets(store, MAX_LINE - 1, fp)){
        char * FirstWord = strtok(store," ");
        char * LastWord;
        char * token = strtok (NULL, " ");
        while (token != NULL){
            LastWord = token;
            token = strtok (NULL," ");
        }
        printf("%s\n",LastWord);
        printf("%s\n",FirstWord);
    }
    fclose(fp);
}

Keep in mind that fgets reads n-1 characters or until it encounters a newline or EOF character. however a newline character is also considered a valid character and stored in the string. That means LastWord may end with a newline character. To fix that, pass " \n" instead of " " to strtok. Then both a newline and a blankspace are considered delimiters.

Related