简体   繁体   中英

Separate scanf input with space in C

I try to input a series of numbers, every number separated by a space. The series of numbers has to stop taking input once a 0 is given.

I do this with a for loop. If I separate every number with \\n , it stops indeed reading input after I have given 0 as a number.

But if I instead separate every number with a space, nothing happens after I give a 0 . It just keeps reading input.

I tried to find an answer, I'm sorry if the solution is obvious. I just started in C, please bear with me..

int main(int argc, char **argv){

    int ar[1000];
    int i;

    printf("Give a series of numbers, separated by space. Stop reading when `input is 0.\n --> : ");`

    for (i = 0; i < SIZE ; i++){
        scanf("%d", &ar[i]);
        if (ar[i] == 0){break;}
    }

   return 0;
}

By default, most command-line terminals will only send input to the running program after you finish typing a whole line. This is to give you a chance to fix typos with the backspace key.

One easy solution is to, instead of typing the input by hand, put it in a text file and use file input redirection ( < ). This input redirection syntax works on both Linux and Windows shells.

myProgram.exe < myInput.txt

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