(C)使用字符串读入值,然后将它们分开并标记化

时间:2015-03-30 18:36:13

标签: c string token tokenize

我在将代码扫描转换为使用字符串方面存在问题,目前它导致命令提示符崩溃。如果有任何额外的信息可以让这更容易,请告诉我。感谢您的任何帮助。

输入(.csv逗号分隔变量电子表格):

PART    2       -1    0.05      V
PART    0.975   -1    0.025     V
PART    3        1    0.01      F
GAP     0        0.08   

我尝试使用字符串:

char ch1,ch2,ch3,ch4,c[3],line[100],*n[100],s[3]=",",*token;
float nom[3],impct[3],tol[3],gapmin,gapmax,tolerance,max_gap,min_gap,gap;
int i;
// ---------------------
char keyPart[] = "PART";
char keyGAP[] = "GAP";
// ----------------------

if (fpin==NULL)     //error checking for file
{
    printf("Error opening file!\n");
    fclose(fpin);
    fclose(fpout);      //close files
}
while ( fgets(line, 100, fpin) != NULL )
{
    strcpy(n, line);
    token = strtok(line,s);
    // -----------------
    if (strcmp(keyPart, token) == 0)
    {
        // PART
        for(i=0; i<3; i++)
        {
            token = strtok(NULL,s);
            nom[i] = strtof(token, NULL);
            token = strtok(NULL,s);
            impct[i] = strtof(token, NULL);
        }
    }
    if (strcmp(keyGAP, token) == 0)
    {
        for(i=0; i<3; i++)
        {
            token=strtok(NULL,s);
            gapmin=strtof(token, NULL);// GAP
            token= strtok(NULL,s);
            gapmax= strtof(token, NULL);
        }
    }
    while(token != NULL)
    {
        printf("%s\n", token);
        token = strtok(NULL,s);
    }
}

我的代码在字符串之前(正常运行)

for(i=0;i<4;i++)    //loop to scan in values
{
    fscanf(fpin,"%c%c%c%c,",&ch1,&ch2,&ch3,&ch4);     //scan in four characters

    if (ch1=='P' && ch2=='A' && ch3=='R' && ch4=='T' )    //If the characters spell PART...
    {
        fscanf(fpin,"%f,%f,%f,%c\n", &nom[i],&impct[i],&tol[i],&c[i]);   //scan in values
        printf("%f,%f,%f,%c\n",nom[i],impct[i],tol[i],c[i]); //print the values
    }

    if(ch1=='G' && ch2=='A' && ch3=='P')     //If Characters spell GAP...
    {
        fscanf(fpin,"%f,%f",&gapmin,&gapmax);   //scan in values
    }
}

编辑: 至少现在消除崩溃:

for(i=0; i<3; i++)
        {
            token = strtok(NULL,s);
            nom[i] = strtof(token, NULL);
            //token = strtok(NULL,s);
            impct[i] = strtof(token, NULL);
            //printf("\n%f\n%f\n",nom[i],impct[i]);
        }
    }
    if (strcmp(keyGAP, token) == 0)
    {

            token=strtok(NULL,s);
            gapmin=strtof(token, NULL);// GAP
            //token= strtok(NULL,s);
            gapmax= strtof(token, NULL);
            //printf("\n%f\n%f\n",gapmin,gapmax);

    }
    while(token != NULL)
    {
        token = strtok(NULL,s);
        printf("%s\n", token);

    }
}

0 个答案:

没有答案