Home > Software design >  How to parse a line into different variables in C?
How to parse a line into different variables in C?

Time:05-17

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

 FILE* file=fopen(fileName, "r");

 if(file==NULL)
 {
 perror("Error opening file.");
 }
 else
 {
 char line[255];
fgets(line,255,file);

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


}
 void splitLine(char line[], int length)
 {
 int rowLength=0;
 int columnLength=0;
 int array[3];
 int count=0;
 char character;

 char *ptr=strtok(line, " ");

 while(ptr!=NULL)
 {
 array[count]=atoi(ptr);
 ptr=strtok(NULL, " ");
 count  ;

 }

 rowLength=(array[0]);
 columnLength=(array[1]);
 character=(array[2]);
 printf("%d,",rowLength);
 printf("%d,",columnLength);
 printf("%c\n",character);

 }

CodePudding user response:

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

    //...
}    

CodePudding user response:

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