getting numbers from stdin to an array in C

MinaHany picture MinaHany · Apr 8, 2012 · Viewed 11.1k times · Source

I'm trying to get numbers from stdin to an array. the first number in stdin is the number of elements in the array (the number can be any int). I did this to get the first number:

while(c=getchar()!=' '){
n*=10;
n+=atoi(c);
}

And then created an array of size n. Now I need to go through all the rest

 while(c=getchar()!=EOF)

and add numbers to the array. The numbers are separated by \t and sometimes \n as well. How would I do that? I've been thinking for an hour and still haven't got a working code. Any help? Thanks!

Answer

Jerry Coffin picture Jerry Coffin · Apr 8, 2012

Unless you're feeling particularly masochistic (or can't due to homework requirements), you'd normally do it using scanf:

int n;
int *numbers;

scanf("%d", &n);

numbers = malloc(n * sizeof(*numbers));

for (int i=0; i<n; i++)
    scanf("%d", &numbers[i]);

For more robust error handling, you frequently want to read a line at a time using fgets, then parse that into individual numbers using sscanf (or something similar).

As an aside: no you should not cast the return from malloc to int *. It's neither necessary nor desirable in C. Just #include <stdlib.h>, and assign the result as shown above. If your compiler is giving you a warning (or error) about a conversion, that means one of two things is happening: either you've forgotten to #include <stdlib.h> as required, or else you're actually compiling as C++. If you're writing C++, write real C++, which means you shouldn't be using malloc at all.