fgets()
reads into a string (array of char
), not an array of int
.
Your loop should be:
char line[4096];
while (fgets(line, sizeof(line), stdin) != 0)
{
...code using sscanf() iteratively to read into the array of int...
}
Not checking inputs leads to problems. At best, your code would process the last line of input twice, most likely. You're only allowed to do that if it means that my refund gets processed twice. At worst, your code might never terminate until your program gets bored to death, or runs out of memory, or you lose patience with it and kill it.
[This] doesn't answer the question of how I would write to the array within the while loop. Would I enclose the sscanf
function in a for
loop for however many numbers got entered? Would I set something up to run each time Enter is pressed?
Given that you only have one number per line, then the code in the body of the loop is simple:
char line[4096];
int array[1024];
int i = 0;
while (fgets(line, sizeof(line), stdin) != 0)
{
if (i >= 1024)
break; // ...too many numbers for array...
if (sscanf(line, "%d", &array[i++]) != 1)
...report error and return/exit...
}
Note that this code won't notice if there is garbage (other numbers, non-numbers) on the same line; it simply grabs the first number (if there is one) and ignores the rest.
If you need multiple numbers per line, look at How to use sscanf()
in loops for more information.
If you want a blank line to terminate the input, then using fscanf()
or scanf()
is not an option; they read through multiple blank lines looking for input.