C - Using strtok

97 views Asked by At

I get only 'int' from txt using strtok.

But, the written code has some error.

The output of the first line is good, but it cannot go to next line.

How can I handle this?

while (!feof(fp))

{
    fgets(buffer, 100, fp);
    printf("%s", buffer);
    num = strtok(buffer, " ,\t\n");
    i = atoi(num);
    while (num != NULL){
        printf("num = %s\n", num);
        num = strtok(NULL, ",\n");
        x = atoi(num);
        num = strtok(NULL, "\t");
        y = atoi(num);
        printf("i = %d, x = %d, y = %d\n", i, x, y);
    }
}

text file :

1   1,1   2,2    3,3
2   1,2   2,4    3,6   4,8
3
4   1,4
5
2

There are 2 answers

0
Horacio On

The question you ask seems not to be completely clear.

  • If you want to parse an integer number followed by an variable series of real numbers the problem is that you are using a comma instead of a dot as a decimal point.

  • Variables i, x, and y seem to be global (are they int?) because they are not declared into the block of code, but they receive an int value provided by atoi() -array to integer. Apart from that, some lines may have more than three values.

  • The delimiters you are using in strtok() don't seem to match with the actual delimiters of the text.

  • You are processing a line read by fgets() before verifying that the end of file has not been reached.

0
BLUEPIXY On

a way of sample to fix

while (fgets(buffer, sizeof buffer, fp)){
    num = strtok(buffer, " ,\t\n");
    i = atoi(num);
    num = strtok(NULL, " ,\t\n");
    while (num != NULL){
        x = atoi(num);
        num = strtok(NULL, " ,\t\n");
        y = atoi(num);
        printf("i = %d, x = %d, y = %d\n", i, x, y);
        num = strtok(NULL, " ,\t\n");
    }
}