Question

This code will read a file and print it as long as the file is in this format

word,12,34
words,40,20
another,20,11

How do I get it to do the same if its got an empty line in between like this because right now it just gives me a segmentation fault

word,12,34

words,40,20

another,20,11



#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
    FILE *pdata;
    char buffer[1000];
    char *token, *del=",";
    int value1;
    double value2;


    pdata = fopen ("file.data", "r");

    if(pdata == NULL)
    {
        printf("unable to open file \n");
        exit(1);
    }

    while( fgets(buffer, sizeof(buffer), pdata) != NULL )
    {
        token = strtok(buffer, del);
        value1 = atoi( strtok(NULL, del) );
        value2 = atof( strtok(NULL, del) );

        printf("%s is %.3lf\n", token, value1 + value2);

    }

    fclose( pdata );


return 0;
}   

Please Help

Was it helpful?

Solution

Two changes I would make:

char *del = ", "; // test for either space or comma

And (per my comment to the question earlier):

while( fgets(buffer, sizeof(buffer), pdata) != NULL )
{
    char *temp;
    token = strtok(buffer, del);
    if (token != NULL) {
      temp = strtok(NULL, del);
      if (temp) value1 = atoi( temp );
      temp = strtok(NULL, del);
      if (temp) {
        value2 = atof( temp );
        printf("%s is %.3lf\n", token, value1 + value2);
      }
}

The strtok will return NULL if no token is found. Passing a NULL string to atoi is what's giving you the seg fault, I'm guessing. Like this, we make absolutely sure that doesn't happen. I tested this and it works.

OTHER TIPS

while( fgets(buffer, sizeof(buffer), pdata) != NULL )
{
    if (buffer[0] == '\n') {
        /* empty line */
        continue;
    }
    token = strtok(buffer, del);
    value1 = atoi( strtok(NULL, del) );
    value2 = atof( strtok(NULL, del) );

    printf("%s is %.3lf\n", token, value1 + value2);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top