1
votes

I'm attempting to write a small program where a user specifies they wish to enter n many nunmbers, then they are prompted to enter n many floats in the subsequent lines with a prompt. The expected output is

$./a.out
How many number (at least two)? > 4
Enter a number (3 more to enter) > 2
Enter a number (2 more to enter) > 3
Enter a number (1 more to enter) > 5
Enter a number (0 more to enter) > 7

However, my program currently reads in the first input (2, in the case of my example), then skips the user input of the rest of the prompts.

The output for my current code is

$./a.out
How many number (at least two)? > 4
Enter a number (3 more to enter) > 7
Enter a number (2 more to enter) > 
Enter a number (1 more to enter) > 
Enter a number (0 more to enter) >

I searched for a solution here, here, and here, but I couldn't get anything to work. Does anyone have any suggestions on how to get scanf to work in this? I'd prefer to use scanf as we haven't covered the usage of any of the gets functions.


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

main(){
    int i,n;
    int temp_count,count,rv;
    float number[10000];
    printf("How many number (at least two)? > ");
    rv = scanf("%d",&n);
    if(n<2||rv!=1){
        printf("Please enter at least two numbers");
    }
    count=n;
    for(i=0;i<n;i++){
        count--;
        printf("Enter a number (%d more to enter) > ",count);
        fflush(stdin);
        scanf(" %.2f",number[i]);
    }
    return(0);
}    //end main

1

1 Answers

1
votes

As user @user3121023 comments (comment now deleted):

scanf("%f",&number[i]); ampersand needed. Do not fflush(stdin);

The last argument to scanf() should be a pointer to the buffer where the input will be stored. In your case, number[i] is a float, not a float *. Adding a & before number[i] will give scanf() the address of the i:th position of the array.

Also, using fflush() on an input stream is a bad idea as it invokes undefined behaviour. It may work, but it may not. See here for reference on fflush().

Note: fflush() on an input stream is well defined by POSIX (not standard C), and only when the stream is seekable. Standard input is generally not seekable.