how to tokenize string to array of int in c?

前端 未结 6 1596
暖寄归人
暖寄归人 2020-12-15 01:01

Anyone got anything about reading a sequential number from text file per line and parsing it to an array in C?

What I have in a file:

12 3 45 6 7 8
3         


        
6条回答
  •  离开以前
    2020-12-15 01:57

    What I would do is to make a function like this:

    size_t read_em(FILE *f, int **a);
    

    In the function, allocate some memory to the pointer *a, then start reading numbers from the f and storing them in *a. When you encounter a newline character, simply return the number of elements you've stored in *a. Then, call it like this:

    int *a = NULL;
    FILE *f = fopen("Somefile.txt", "r");
    size_t len = read_em(f, &a);
    // now a is an array, and len is the number of elements in that array
    

    Useful functions:

    • malloc() to allocate an array.
    • realloc() to extend a malloc()ed array
    • fgets() to read a line of text (or as much as can be stored).
    • sscanf() to read data from a string (such as a string returned by fgets()) into other variables (such as an int array created by malloc() - hint hint)

提交回复
热议问题