0

I'm trying to take up to 10 integer inputs and then print out each one. So if the user enters 4 integers the program would print out those 4 and end the program. If they enter 10 it'll print out all 10. If they enter more than 10, it'll only print out the first 10.

Here's what I have so far:

    int array[10];
    int i = 0;

    while(i < 10 && scanf("%d\n", &array[i]) == 1){
      printf("%d ",array[i]);
      i++;

    }

This doesn't quite work, if I enter 3 numbers it'll print out the first 2, and not print out the third until I hit ctrl-D, and will exit when I hit ctrl-D again.

  • 2
    [Why does printf not flush after the call unless a newline is in the format string?](http://stackoverflow.com/q/1716296/335858) – Sergey Kalinichenko Nov 10 '15 at 01:28
  • Does the user enter the numbers all on one line or on separate lines or some mixture? Data isn't made available to the program until the newline is typed (unless you type control-D). Data doesn't appear on the output until you print a newline. – Jonathan Leffler Nov 10 '15 at 01:38
  • @JonathanLeffler Any mixture, just until they use ctrl-D – Grant Seltzer Nov 10 '15 at 01:44
  • 1
    They'll have to type control-D twice if they don't type it immediately after a beeline. – Jonathan Leffler Nov 10 '15 at 01:45
  • 1
    a couple of problems with the posted code. 1) this line: `while(i < 10 && scanf("%d\n", &array[i]) == 1){` should be: `while(i < 10 && scanf("%d", &array[i]) == 1){` 2) after this line: `}` at the end of the while loop, insert `printf( "\n" );` which will print all the numbers on a single line. If you want each number on a separate line, change this line: `printf("%d ",array[i]);` to `printf("%d\n",array[i]);` – user3629249 Nov 11 '15 at 05:33

1 Answers1

2

scanf("%d\n" does not return until non-white-space (or EOF) occurs after the int.

To get it to return after the int, use scanf("%d"

chux - Reinstate Monica
  • 113,725
  • 11
  • 107
  • 213