-1
#include <stdio.h>
#define length 20
main()
{
    float x;
    int y;
    float array1[length], array2[length], array3[length];
    float ray[length];
    int size1 = insert(array1, length);
    printf("enter number: ");
    scanf("%d", &y);
    int size2 = insert(array2, length);
    int size3 = insert(array3, length);
}

int insert(float a[], int size)
{
    int  n = 0;
    while(n<size && scanf("%f\n", &a[n]) == 1)
    {
        printf("you entered: ");
        printf("%2.1f\n", a[n]);
        n++;
    }
    return n;
}

When I run the program, it executes the first insert okay, but the next time function is called, scanf() seems to be ignored completely. I tried putting it right after where insert is done, but that's ignored as well.

Gravity Mass
  • 605
  • 7
  • 13
sajax63
  • 11
  • 5

2 Answers2

0

Use %*c in scanf to consume the newlines along with space around %d in the scanf in main(). I tested the below code on MingW and it seem to work. The '\n' in your scanf is being consumed making it scanf() return while the '\n' at the press of enter key still remains in IO buffer to be consumed by scanf() again; hence the weird behaviour.

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

#define length 20

int insert(float *a, int size)
{
    int  n = 0;
    while(n<size && scanf("%f%*c", &a[n]))
    {
        printf("you entered: ");
        printf("%2.1f\n", a[n]);
        n++;
    }
    return n;
}

int main(int argc, char* argv[])
{
float x;
    int y;
    float array1[length], array2[length], array3[length];
    float ray[length];
    int size1 = insert(array1, length);
    printf("enter number: ");
    scanf("%d", &y);
    int size2 = insert(array2, length);
    int size3 = insert(array3, length);
    return 0;    
}
anurag-jain
  • 1,380
  • 2
  • 11
  • 31
0

In the scanf format string, change "%f\n" to "%f". The \n in a scanf format string does not mean "wait for newline".

You do not need to worry about waiting for newline, because the only format specifiers you use are %f and %d, which both discard any leading whitespace.

M.M
  • 138,810
  • 21
  • 208
  • 365