Home > Back-end >  Reading from csv file in C causing input to not print
Reading from csv file in C causing input to not print

Time:09-25

I am trying to read data from a csv file input below:

0, 0
5, 0
7, 0

This input is supposed to be x and y coordinates where x= 0 and y =0 and x=5 and y=5 and so on....

What i have tried

I am trying to print the numbers and then store each one. I can't store them or print them correctly as I am new to C and I am finding it difficult

Required output:

x:0      y:0
x:5      y:0
x:7      y:0

This is my code below:

#include <stdio.h> 
#include <stdlib.h>   
#include <curses.h> 
#include <string.h>

int main()
{
    FILE* fp = fopen("points.csv", "r");
    if (!fp)
        printf("Can't open file\n");
    else {
        char buffer[1024];
        int row = 0;
        int column = 0;
        int distance;

        while (fgets(buffer,
                    1024, fp)) {
            column = 0;
            row  ;
            if (row == 1)
                continue;

            // Splitting the data
            char* value = strtok(buffer, ",");
   
            while (value) {
                // Column 1
                if (column == 0) {
                    printf("x:");
                }
                // Column 2
                if (column == 1) {
                    printf("\ty:");
                }
                printf("%s", value);
                value = strtok(NULL, ", ");
                column  ;
            }
        // distance = ((x2-x1) *(x2-x1))   ((y2-y1) * (y2-y1));
            printf("\n");
        }
        fclose(fp);
    }
    return 0;
}

CodePudding user response:

Since your file contains only two columns, you can write it this way using sscanf():

#include <stdio.h>
#include <string.h>

int main()
{
    FILE *fp = fopen("file", "r");
    if (!fp) {
        fprintf(stderr, "Can't open file\n");
        return 1;
    }
    
    char line[1024];
    int x, y;
    while (fgets(line, sizeof line, fp)) {
        line[strcspn(line, "\n")] = '\0'; // Replace '\n' read by fgets() by '\0'

        if (sscanf(line, "%d, %d", &x, &y) != 2) {
            fprintf(stderr, "Bad line\n");
        }
        
        printf("x:%d\ty:%d\n", x, y);
    }
    
    fclose(fp);
}
  • Related