tags:

views:

703

answers:

2

Hi, I'm writing an app in pure C which expects two line at input: first one, which tells how big an array of int will be, and the second, which contains values, separated by space. So, for the following input 5 1 2 3 4 99 I need to create an array containing {1,2,3,4,99}

Now, my question is - what is the fastest (yet easy ;)) way to do so? My problem is "how to read multiple numbers without looping through the whole string checking if it's space or a number" ?

Thanks m.

A: 

scanf() is kind of a pain in the ass. Check out strtol() for this kind of problem, it will make your life very easy.

Carl Norum
together with strtok it might be interesting, but I have no idea how to read the whole line at first ;/
migajek
@michal, `fgets()` will read a line. I don't know why you would need `strtok()` for your problem.
Carl Norum
+1  A: 
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()

Denilson Sá
I thought it'll look for numbers separated by "\n"?
migajek
`%d` (as well as most % conversions, but not all of them) automatically skips any whitespace. Read the scanf documentation for details!
Denilson Sá
"If for some reason"? You should never use `scanf` and should prefer using `fgets` with `sscanf`. http://c-faq.com/stdio/scanfprobs.html
jamesdlin
@jamesdlin, sorry, but I disagree. If you really *know* how to use scanf, you can use it safely. And by knowing I mean really understanding all options and conversions from scanf. (read the entire manpage)
Denilson Sá
The fact that it can leave unprocessed input in the input buffer should make you cringe. Yes, there are ways you can use `scanf` safely, but all the hoops you have to jump through simply don't make it worthwhile. `fgets` with `sscanf` is much simpler and has fewer gotchas for the uninitiated.
jamesdlin