0

I used fgets() to read input of a file into a

char buf[10];

the input of the file is

10,10,4,10

I want to iterate through the line and store each number in the char array as its own individual integer value but I am a little lost on how to do that. If someone could point me in the right direction I'd really appreciate it, thanks!

Yun
  • 3,056
  • 6
  • 9
  • 28
ell
  • 25
  • 4

1 Answers1

0

There are different approaches to do this. If you are learning C, I would recommend writing your own by-hand solution and after understanding how it works, use some standard library functions like strtok as @Jeff Holt said.

The easiest approach is to create a variable which will be the current number which we are reading and iterate over the buf array and at each step check if the current character is a number or not.

See this question about converting characters to integers.

So the result will be something like that:

const int size = 10;

char buf[size];
// fill buf, but be sure that input is less than 10 characters

//create array for result
char result[size];
int result_size = 0;

//can also be char, but if input numbers are big enough, it might overflow
int current_value = 0;

for (int i = 0; i < size; i++) {
    if (buf[i] >= '0' && buf[i] <= '9') {
        //convert to int and add to current_value      
    } else {
        //store parsed integer
        result[current_size] = current_value;
        current_size++;
        current_value = 0;
    }
}
elo
  • 489
  • 3
  • 13