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!
Unless you’re feeling particularly masochistic (or can’t due to homework requirements), you’d normally do it using
scanf:For more robust error handling, you frequently want to read a line at a time using
fgets, then parse that into individual numbers usingsscanf(or something similar).As an aside: no you should not cast the return from
malloctoint *. 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 usingmallocat all.