Partially filled arrays

Someone please help me out here.

I'm trying to fill an int array with values from stdin.
The user enters values one per line. When anything other than a number is
entered,the while loop should stop, leaving the remainder of the array
untouched.
Instead, here is how it works.
If very first entered value is not a number, the program exits the loop
just like I want it to. But, if not a number value has been entered second or
third and so on.., the loop goes into infinity. Without even stopping at the 'scanf'!!! And the val variable remains the last numerical value that has been entered.
What is going on? Please help.

1
2
3
4
5
6
7
8
  int val=1;
  int i=0;
  scanf("%i", &val);
  while(val != 0){
   arr[i] = val;
   scanf("%i",val);
   i++;
  }
You need to check the return value of scanf. Go look at the documentation for information on what it means.
The documentation would help if I was an ace programmer. But since I'm a noob,
all that fancy talk is way over my head. The documentation in fact, is just a little
bit less ambiguous than C itself. How am I supposed to decipher, why the program
skips scanf inside the loop? All I know is that it is supposed to stop there and weight for an input.
Do you understand what is happening there?
"noob" is not a valid excuse.

Return Value
On success, the function returns the number of items of the argument list successfully filled.

Therefore,
1
2
3
4
5
6
7
8
9
  int val=0;
  int i=0;
  int got = 0;
  got = scanf("%i", &val);
  while( 1 == got ){
   arr[i] = val;
   got = scanf("%i", &val);
   ++i;
  }

Besides, your line 3 passes the address of val, but line 6 passes the value of val.
Ok. So...
It looks like scanf can act on two variables at the same time.
If used this wayscanf("%i", &val);, it just reads the value
from stdin into 'val'.
And if used this waygot=scanf("%i", &val);, than in addition
to assigning a value to val, it also assigns a value of 0, or 1, or EOF to 'got'.
Am I right?
No matter which way you use the function, it will return a value. In the first snippet, you just ignore the return value. In the second snippet, you capture it.
Got it.
Thank you everybody!
I'm moving on to a next block of code.
Topic archived. No new replies allowed.