Tibi Tmbs
Tibi Tmbs

Reputation: 11

Strtok deletes last char before delimiter

I'm trying to read a file using fgets and tokenise it with strtok but somehow im losing the last char of the first token(title). Ive been trying for a while to fix this but cant seem to do it any help is appreciated. I've though of adding a char just before the delimiter but im not quite sure how to implement that.

char line[201];
char *title;
int year;
char *age;
char *genre;
int lenght; 
float rating;
while ((fgets(line,sizeof(line),fp)) != NULL){
    strtok(line,"\"");
    title = line;
    year = atoi(strtok(NULL,","));
    age = strtok(NULL,",");
    memmove(age, age+1, strlen(age));
    genre = strtok(NULL,",");
    memmove(genre, genre+1, strlen(genre));
    lenght = atoi(strtok(NULL,","));
    rating = atof(strtok(NULL,","));
    x = new_film(title,year,age,genre,lenght,rating);
    Insert(root, x);
}

file data looks like this :

"The Good, the Bad and the Ugly",1966,"APPROVED","Western",161,8.9 "Memento",2000,"R","Mystery/Thriller",113,8.5

output looks like this:

The Good, the Bad and the Ugl,1966,APPROVED,Western,161,8.9

Upvotes: 0

Views: 833

Answers (2)

user3629249
user3629249

Reputation: 16540

note: the 'title' has a leading delimiter,

you should be VERY careful when the next character to be check is a delimiter.

Strongly suggest always use a delimiter of , (comma) for your current data example.

If you want to (later) remove any ``"` (double quotes) then the surrounding double quotes will still be there to and can be easily removed.

Lets remember that strtok() replaces the delimiter with a NUL byte, so the first call (in the posted code) to strtok() will have already trimmed the trailing double quote

Upvotes: 0

Weather Vane
Weather Vane

Reputation: 34575

You have a confusion of ignoring the return value from strtok and trying to fiddle the strings it is separating. I suggest this (although you should always check for bad data formatting, for example when strtok returns NULL):

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

int main(void)
{
    char line[201];
    char *title;
    int year;
    char *age;
    char *genre;
    int lenght; 
    float rating;
    while ((fgets(line,sizeof(line),stdin)) != NULL){

        title = strtok(line, "\"");                 // use this value
        year = atoi(strtok(NULL, "\",\n"));         // added delimiters
        age = strtok(NULL, "\",\n");
        genre = strtok(NULL, "\",\n");
        lenght = atoi(strtok(NULL, "\",\n"));
        rating = (float)atof(strtok(NULL, "\",\n"));

        printf("%s\n", title);
        printf("%d\n", year);
        printf("%s\n", age);
        printf("%s\n", genre);
        printf("%d\n", lenght);
        printf("%f\n", rating);
        printf("\n");
    }
    return 0;
}

Program output:

The Good, the Bad and the Ugly
1966
APPROVED
Western
161
8.900000

Memento
2000
R
Mystery/Thriller
113
8.500000

Upvotes: 1

Related Questions