0

I have two files, 2dim.dat and 3dim.dat, which respectively contain the following in their 3rd line:

2 12

and

1 0 0

Their 3rd line is the only one relevant to our interest. A function is written that computes for us how many numbers will there be in that line, and the program then constructs an array of unsigned ints with that many dimensions. I know I can assign the values 2 and 12 from 2dim.dat into the dimensions of that array in a C program by doing

if(fscanf("%hu %hu", &number[0], &number[1]) == 2){}

It is similarly done for 3dim.dat.

What if I receive a file that contains more values in a line, like 4, 20 or even 270? I don't know how to tell fscanf to have 270 repeats of %hu separated with spaces in its first argument and then add all dimensions of our array.

1 Answers1

0

sample code

#include <stdio.h>

int main(void){
    //input line_buff like fgets(line_buff, sizeof(line_buff), fp);
    char line_buff1[64] = "4 20 270";
    char line_buff2[64] = "4 20";
    unsigned short number[3];
    int i, count;
    //Succeed in reading three, be count = 3
    count = sscanf(line_buff1, "%hu %hu %hu", &number[0], &number[1], &number[2]);
    for(i=0;i<count;++i)
        printf("%hu\n", number[i]);

    //Succeed in reading two, be count = 2, fail number[2]
    count = sscanf(line_buff2, "%hu %hu %hu", &number[0], &number[1], &number[2]);
    for(i=0;i<count;++i)
        printf("%hu\n", number[i]);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70