2

I need the program to exit the while loop if the user presses enter without entering any float value. Thanks!

printf("Enter scores\n”);

float scores[10];
int n=0;    

while (n<10){

    scanf("%f", &scores[n]);
    n++;
    if (THE USER PRESSES ENTER WITHOUT ENTERING ANYTHING){break;}

}
Jordan Wiley
  • 21
  • 1
  • 1
  • 2

5 Answers5

5

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
ad absurdum
  • 19,498
  • 5
  • 37
  • 60
2

Separate input of user text from parsing.
Read the line of user input as a string;

char buffer[80];
if (fgets(buffer, sizeof buffer, stdin) == NULL) Handle_EOF();

Now, parse the string using sscanf(), strtod(), etc.

if (sscanf(buffer, "%f", &scores[n]) == 1) Handle_Successful_Float_Input(scores[n]);
else if (buffer[0] == '\n') Handle_Empty_Line();
else Handle_Everything_Else(buffer);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

fgets is the better route but if scanf must be used, newline can be detected by scanning a character. If the character is not a newline, replace it in the input with ungetc and then scan the float.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SIZE 10

int main ( void) {
    char i = '\0';
    int n = 0;
    int result = 0;
    float scores[SIZE] = { 0.0f};

    printf ( "enter scores\n");
    while ( n < SIZE && ( scanf("%c",&i) == 1)) {//scan a character
        if ( i == '\n') {
            break;//newline so leave loop
        }
        else {
            ungetc ( i, stdin);//replace the character in input stream
        }
        if ( ( result = scanf ( "%f", &scores[n])) == 1) {//scan a float
            printf ( " score[%d] entered as %f\n", n, scores[n]);
            n++;
        }
        if ( result == 0) {
            printf ( "please enter a number\n");//could not scan the input as a float
        }
        while ( ( result = getchar ( )) != '\n') {//clean the input stream
            if ( result == EOF) {
                fprintf ( stderr, "problem EOF\n");
                return 1;
            }
        }
        printf ( "enter score[%d]\n", n);
    }
    return 0;
}
xing
  • 2,125
  • 2
  • 14
  • 10
-1

I thought . you want to check that if an integer is assigned a value or not ? Actually you have to initialize the variable otherwise it will contain whatever happen at that memory location unless it is declared as global. If you are not getting then check this might help you with your question

Community
  • 1
  • 1
  • 1
    The code is reading floating point numbers, not integers. I think you've missed the point of the question — which is about detecting when a blank line is entered while using the `scanf()` family of functions. – Jonathan Leffler Feb 16 '17 at 06:09
-2

We know that scanf returns a negative value if nothing of the defined type is fetched from the input.

So:

printf("Enter scores\n”);

float scores[10];
int n=0;    

while (n<10){

    if(scanf("%f\n", &scores[n]) < 0) printf("Error! Error!");

    n++;
}

See http://www.cplusplus.com/reference/cstdio/scanf/

BearAqua
  • 518
  • 4
  • 15
  • 1
    But it doesn't stop looking just because it sees a newline. – rici Feb 16 '17 at 04:56
  • 2
    `scanf()` returns `EOF` only if end-of-file is reached before any matches are made. But, `scanf()` returns when the first non-match is encountered, or end-of-file is reached. So, 0 is returned if no conversions are made, unless eof is reached. You should test `scanf() != 1`. And, the `%f` conversion skips leading whitespace, including newlines, anyway. – ad absurdum Feb 16 '17 at 05:07
  • 1
    @AlexFang-- that won't work. This is one of the subtleties of `scanf()`. If you put a white-space character at the end of a format string, `scanf()` will continue greedily asking for more input until a non-white-space character is encountered (or `EOF` is reached). The result is that input blocks until the user enters a non-white-space character or signals `EOF` from the keyboard. See [§7.21.6.2](http://port70.net/~nsz/c/c11/n1570.html#7.21.6.2) of the C11 Draft Standard, in particular [paragraph 5](http://port70.net/~nsz/c/c11/n1570.html#7.21.6.2p5). – ad absurdum Feb 16 '17 at 18:25
  • BTW, not a downvoter, I was just trying to point out that `scanf()` does _not_ necessarily return "a negative value if nothing of the defined type is fetched from the input." Your test should be `!= 1` instead of `< 0`. But, even at that, `scanf()` will not read an empty line here, since the `%f` conversion skips over leading white-space. – ad absurdum Feb 16 '17 at 18:31