简体   繁体   中英

How to take up to a certain amount of inputs in C

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM