0

So I want to read user input array of UNKNOWN number of values ,eg: 1.0 3.0 -2.0.... etc, naturally I did scanf("%s", array) first and realized that it would only read until first space, and then I attempted the following:

#include <stdio.h>

int main()
{
    printf("enter array: ");
    char str[100];
    fgets(str, 100, stdin);
    printf("%s", str);

return 0;
}

That itself works, however when I incorporated it into the rest of my code it does not work it just skips the input of the array

#include <stdio.h>

int main()
{
    float a, b;
    int t;

    printf("A: ");
    scanf("%f",&a);
    printf("B: ");
    scanf("%f",&b);
    printf("T: ");
    scanf("%d",&t);

    printf("enter array: ");
    char str[100];
    fgets(str, 100, stdin);
    printf("%s", str);

return 0;
}

What am I doing wrong please help

jl123
  • 1

1 Answers1

1

This seems to be because of a trailing newline in the stdin stream, when you do a scanf("%d",variable) and input some integer and press enter, only the integer is read and the trailing newline from the pressing of the return key is left in the input stream. So when you call fgets() this newline gets read and the function immediately exits. You can find an explanation for it in the C Faq.

There are multiple solutions for this, for one you can simply eat up the newline using

while(getchar()) != '\n') {
/* do nothing and discard the character */};

printf("enter array: ");

you can also see this question and this one for some more details.

phoney_badger
  • 462
  • 3
  • 10