Search code examples
cio

fscanf in C - how to determine comma?


I am reading set of numbers from file by fscanf(), for each number I want to put it into array. Problem is that thoose numbers are separated by "," how to determine that fscanf should read several ciphers and when it find "," in file, it would save it as a whole number? Thanks


Solution

  • This could be a start:

    #include <stdio.h>
    
    int main() {
        int i = 0;
    
        FILE *fin = fopen("test.txt", "r");
    
        while (fscanf(fin, "%i,", &i) > 0)
            printf("%i\n", i);
    
        fclose(fin);
    
        return 0;
    }
    

    With this input file:

    1,2,3,4,5,6,
    7,8,9,10,11,12,13,
    

    ...the output is this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    

    What exactly do you want to do?