简体   繁体   中英

How to parse a line into different variables in C?

I have a simple file, with integers and characters to be read. I read line by line and stored them in a char array and then split from the whitespace using strtok() and converted to int variables using atoi(), but I can't extract the single character into a char variable.[![enter image description here][1]][1]

For starters this code snippet

fgets(line,255,file);

while (fgets(line,255,file))
{
  splitLine(line, 255);
  fgets(line,255,file);
  splitLine(line, 255);
}

is unsafe because you do not check the result of each call of fgets .

The second parameter of the function splitLine is redundant because the first passed argument represents a string

So declare the function like

void splitLine( const char line[] );

Within the function it is better to use sscanf instead of strtok . Moreover for a character symbol to call atoi does not make a sense

array[count]=atoi(ptr);

The function can look the following way

void splitLine( const char line[] )
{
    int rowLength;
    int columnLength;
    char character;

    if ( sscanf( line, "%d %d %c", &rowLength, &columnLength, &character ) == 3 )
    {
        printf("%d,",rowLength);
        printf("%d,",columnLength);
        printf("%c\n",character); 
    }

    //...
}    

You are doing a different thing for each column, so why use an array?

char *ptr=strtok(line, " ");
for (count=0; i < 3; i++) {
    if (ptr == NULL)
        break;
    switch(count) {
    case 0:
        rowlength = atoi(ptr);
        break;
    case 1:
        columnLength = atoi(ptr);
        break;
    case 2:
        character = *ptr;
        break;
    }
    ptr=strtok(NULL, " ");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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