First off, massive kudos for testing the return value from scanf
, most people just blindly assume it works. It's just a shame you're using it in the wrong way :-)
You want the loop to continue as long as the return value is 1
, meaning that you managed to scan an integer. That means it should be:
while (scanf ("%d", &i) == 1) {
That also means that any non-numeric input will cause scan failure and hence the while
loop will exit. So, if you enter:
3 1 4 1 5 9 stop
you should successfully see the numeric values from the array.
The only other thing is to clean up your j
handling since the k
loop will stop early. This can be done with:
for (k = 0; k <= j; k++) {
Alternatively, leave that loop alone and just change how you initialise and modify j
:
int j = 0;
:
arra[j++] = i;
I tend to find the second choice more C-like since j
is then a count of the elements in the array rather than the maximum index.
And, of course, you're open to a buffer overflow attack at the moment since you assume nobody will enter more than a hundred numbers. So, don't use this as a homework solution (what you have is good enough with the slight bug fixes) but I'd tend to write it as something like:
#include<stdio.h>
#define SZ 100
int main (void){
int arra[SZ], i, nxt = 0;
while ((nxt < SZ) && (scanf ("%d", &(arra[nxt])) == 1))
nxt++;
printf ("\n");
for (i = 0; i < nxt; i++)
printf ("%d ", arra[i]);
return 0;
}