从 C 中的 csv 文件读取导致输入不打印

Reading from csv file in C causing input to not print

我正在尝试从下面输入的 csv 文件中读取数据:

0, 0
5, 0
7, 0

此输入应该是 x 和 y 坐标,其中 x= 0y =0x=5y=5 等等....

我试过的

我正在尝试打印数字,然后存储每个数字。我无法正确存储或打印它们,因为我是 C 的新手,而且我发现这很困难

要求输出:

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

下面是我的代码:

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

因为你的文件只包含两列,你可以这样写 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")] = '[=10=]'; // Replace '\n' read by fgets() by '[=10=]'

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