Your scanf()
is not messing up your a[0]
, at least not in the way you seem to think, by somehow corrupting its storage area. This is very much an issue with mixing different "methods" of input.
What is actually happening with yourscanf/fgets
combo is that the scanf
is getting the integer, but not reading the newline that you enter at the end of that number, so the first fgets
picks that up.
The ISO standard states it thus (in the specified sequence):
Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier.
An input item is read from the stream, unless the specification includes an n specifier. An input item is defined as the longest sequence of input characters which does not exceed any specified field width and which is, or is a prefix of, a matching input sequence.
The first character, if any, after the input item remains unread.
That first and last paragraph is important. The first means the leading whitespace is skipped, the last means that trailing whitespace is left in the input stream to be read later.
However, I'll tell you what may mess it up (depending on the lengths of your input lines), it's the fact that you allocate 50 characters space for each a[i]
then read up to 100 characters into it. Thats undefined behaviour right there.
If you want a robust input solution that handles buffer sizes correctly, detects lines that are too long, throws away the remainders of those lines and so on, see this answer.
Alternatively, if you want to emulate line-based behaviour with the non-line-based scanf
(and you're sure that your lines are always less than 100 bytes), you can change:
scanf("%d", &num);
into:
char junk[100];
scanf ("%d", &num);
fgets (junk, sizeof (junk), stdin);
so that it grabs and throws away the rest of the line.
And you should ensure that the maximum-size argument to fgets
matches the amount of memory available (such as by using sizeof
in the above code).
One other thing, please don't complicate code by multiplying things by sizeof(char)
- that value is always 1 as per the standard.