scanf requires more inputs than requested [duplica

2019-09-07 04:58发布

问题:

This question already has an answer here:

  • Store data in array from input [duplicate] 2 answers
  • Why does scanf ask twice for input when there's a newline at the end of the format string? 6 answers

I'm trying to get 5 float values from the user using scanf, the problem is the user is required to input 6 values for the program to complete. Although I know I shouldn't use scanf, it bothers me that there's something I can't grasp about it. Any insights, any advice on how to fix it whilst using scanf?

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

int main()
{
int i = 0 , j = 0;
char buf[128] = {0};

float numbers[5] = {0.0};
float keep = 0.0;

printf("Please input 5 numbers : \n");

for (i = 0; i < 5; i++)
{
 scanf("%f\n", &numbers[i]);
}

printf("Done!");

Thanks,

MIIJ

回答1:

you must remove \n in scanf() function

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

int main()
{
    int i = 0 , j = 0;
    char buf[128] = {0};

    float numbers[5] = {0.0};
    float keep = 0.0;

    printf("Please input 5 numbers : \n");

    for (i = 0; i < 5; i++)
    {
        scanf("%f", &numbers[i]);
        printf("number %i is %f \n",i,numbers[i]);
    }

    printf("Done!");

    return 0;
}


回答2:

scanf("%f\n", &numbers[i]); should be scanf("%f", &numbers[i]);



标签: c scanf