简体   繁体   English

C-使用strtok

[英]C - Using strtok

I get only 'int' from txt using strtok. 我只有使用strtok从txt中获取“ int”。

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

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. 变量i,x和y似乎是全局变量(它们是int吗?),因为它们没有在代码块中声明,但是它们接收atoi()-array提供给整数的int值。 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. 您在strtok()中使用的定界符似乎与文本的实际定界符不匹配。

  • You are processing a line read by fgets() before verifying that the end of file has not been reached. 在验证尚未到达文件末尾之前,您正在处理fgets()读取的行。

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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM