You can use fgets()
to read a line of input through the newline character into a buffer, and then use sscanf()
to parse the contents of the buffer. The problem with using scanf()
for this is that most conversion specifiers, and in particular the %f
conversion specifier, skip leading whitespace, including newlines. So, if you try to give an empty line to scanf()
, the function will continue to wait for input until you enter a non-white-space character.
The code below adapts this technique to your code. The variable n
has been changed to a size_t
type variable, as this is an unsigned type guaranteed to be able to hold any array index. Furthermore, note that both fgets()
and sscanf()
return values that should be checked. The fgets()
function returns a null pointer if there is an error, and the code below prints an error message and exits if this occurs. The sscanf()
function returns the number of successful conversions made, and this value can be used to make sure that the input is as expected. When the user enters a blank line, or a line with no leading floating point value (leading white-space is OK), zero is returned, and the input loop is escaped.
I added some code to display the values entered into the array.
#include <stdio.h>
#include <stdlib.h> // for exit()
int main(void)
{
float scores[10];
char buffer[100];
size_t n = 0;
printf("Enter scores\n");
while (n < 10){
if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
fprintf(stderr, "Error in fgets()\n");
exit(EXIT_FAILURE);
}
if (sscanf(buffer, "%f", &scores[n]) == 1) {
++n;
} else {
break;
}
}
for (size_t i = 0; i < n; i++) {
printf("scores[%zu] = %f\n", i, scores[i]);
}
return 0;
}
Sample interaction:
Enter scores
3.8
3.6
2.9
3.4
scores[0] = 3.800000
scores[1] = 3.600000
scores[2] = 2.900000
scores[3] = 3.400000