You are reading from the standard input with 2 functions: getchar()
and scanf()
. You need to understand how they work.
getchar()
is easy: it returns the next available character in the input stream (or waits for one or returns EOF
)
scanf("%d", ...)
is more complex: first, it optionally discards whitespace (spaces, enters, tabs, ...), then it reads as many characters as possible to represent an integer, and stops at the first character that can't be used for integers, like a '\n'
.
As you have them in a loop, your getchar()
call will get the character that stopped the scanf()
and the next scanf()
will procedd from there.
If your input is something like "q1w22e333r4444"
(with MAX == 4), your program will work.
If your input is something like
q 1
w 22
e 333
r 4444
after the first time through the loop (where charray[0]
gets 'q'
and inarray[0]
gets 1
), the getchar()
will get '\n'
leaving the 'w'
"ready" for scanf, which of course fails ... and is then "caught" by the next getchar()
; and the "22"
gets assigned in the 3rd time through the loop (to inarray[2]
).
So, you need to review your code.
Also, scanf()
returns a value. Use that value
if (scanf("%d", &inarray[i]) != 1) /* error */;