0

I am writing some code that is supposed to read CSV data from a file and convert it to JSON. I can get this to work with simple values such a floats and ints but with the char src[100] it doesn't seem to print anything. I guess this is related to how the string is terminated but I'm lost. Any guidance on why this happening would be appreciated.

/* Takes CSV data as input and converts it to json */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#define MAX 80

void die(const char *msg)
{
    if(errno)
        perror(msg);
    else 
        printf("%s\n", msg);
    exit(1);
}

int main(int argc, char *argv[])
{
    char src[100];
    //char eqid[MAX];
    int version;
    //char date[MAX];
    float latitude;
    float longitude;
    float magnitude;
    float depth;
    //int nst;
    //char region[MAX];
    int started = 0;

    puts("data_callback ({");
    puts("\"data\": [");
    while(scanf("%s,%d,%f,%f,%f,%f", src, &version, &latitude, &longitude, &magnitude, &depth) == 6) {
         if(started) 
             printf(",\n");
         else 
             started = 1;

         if((latitude < -90.0) || (latitude > 90.0)) {
             die("Latitude out of bounds");
         } 
         else if((longitude < -180.0) || (longitude > 180.0)) {
             die("Longitude out of bounds");
         }
         printf("{\"src:\" %s, \"version\": %d, \"latitude\": %f, \"longitude\": %f, \"magnitude\": %f, \"depth\": %f}", src, version, latitude, longitude, magnitude, depth);

    }
    puts("\n]})");
    return 0;
}

The output:

./convert_to_json
"data": [

Then I paste something such as:

10565ch1,1,64.4679,-148.0767,1.3,11.70

Final output is just an empty line:

"data": [
10565ch1,1,64.4679,-148.0767,1.3,11.70
// should be the json formatted code here
]})

If I run the same program with only the floats and ints I get:

{"version": 1, "latitude": 64.467903, "longitude": -148.076706, "magnitude": 1.300000, "depth": 11.700000}

How do I get this to work with the char? TIA

Ryan Mc
  • 833
  • 1
  • 8
  • 25

0 Answers0