tags:

views:

57

answers:

2

The way being suppose the data is 123 134 2312 32131 2131231 211212

It should take them as different numbers and store them in an integer array .

+2  A: 

You can use fscanf with %d format specifier to read successive integer values from a text file.

Andreas Brinck
+1  A: 
int i = 0, cap = 10;
int *a = malloc(cap * sizeof(int));
int n;
while (scanf("%d", &n))
{
    if (i == cap)
        a = realloc(a, (cap *= 2) * sizeof(int));
    a[i++] = n;
}
Marcelo Cantos
feof() does not do what you seem to think it does
anon
I think a better approach would have been to keep reading until `fscanf` doesn't return 1 (the number of fields read).
Andreas Brinck
It checks for end-of-file on stdin, which marks either Ctrl+D or a closed pipe. Maybe I'm just too tired, but I can't see what's missing.
Marcelo Cantos
Good point Andreas. Is that what you were referring to, Neil? Amended (and fixed a bug in scanf too).
Marcelo Cantos
@Marcelo feof() is only meaningful _after_ you have tried to read something
anon
`feof` checks if the last file operation hit end of file. So your original code would've have tried to read one value if given an empty file
Andreas Brinck
Neil, I have never heard of this. The Open Group [entry](http://opengroup.org/onlinepubs/007908799/xsh/feof.html) doesn't mention it, and even the [example](http://www.cplusplus.com/reference/clibrary/cstdio/feof/) at cplusplus.com calls feof before any operations (other than opening the file) have been invoked. I agree that my original code had a problem with assuming scanf works, but assuming I had fixed it by using `n` only if `scanf` succeeds, but keeping the `feof` test for the while loop, the behaviour would be correct, wouldn't it?
Marcelo Cantos
@Marcelo Lots of people don't realise this - most of the C++ code that gets posted here loops on the istream::eof() function when it should be looping on the success of the read operation. feof() is intended for testing why a read operation failed, not predicting whether it would succeed.
anon