0

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]

2 Answers 2

0

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

    //...
}    
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Hello, thanks a lot for your response, but still this didn't work for me mate. The integer values are read fine but not the char value. Any reason why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.