Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C, reading multiple numbers from single input line (scanf?)

Tags:

c

c99

scanf

I have written an app in C which expects two lines at input. First input tells how big an array of int will be and the second input contains values separated by space. For example, the following input

5
1 2 3 4 99

should create an array containing {1,2,3,4,99}

What is the fastest way to do so? My problem is to read multiple numbers without looping through the whole string checking if it's space or a number?

Thanks.

like image 459
migajek Avatar asked Mar 29 '10 17:03

migajek


1 Answers

int i, size;
int *v;
scanf("%d", &size);
v = malloc(size * sizeof(int));
for(i=0; i < size; i++)
    scanf("%d", &v[i]);

Remember to free(v) after you are done!

Also, if for some reason you already have the numbers in a string, you can use sscanf()

like image 52
Denilson Sá Maia Avatar answered Sep 23 '22 00:09

Denilson Sá Maia