Accepting any number of inputs from scanf function

妖精的绣舞 提交于 2019-11-30 21:55:22

scanf returns the number of input items that have been successfully matched and assigned, thus it is reasonable to do:

while(scanf(...) == 1)

Now you want to be able to read multiple numbers, each defined on the new line. Then you could simply do this:

int array[100];
int i = 0;

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

note that this reading will stop only if invalid input is entered (for example letter q) or when you input the end-of-input control code, which is Ctrl+Z (on Windows) or Ctrl+D (on Mac, Linux, Unix).

The return value of scanf is the number of input items successfully matched and assigned, so try this to end when a non-numeric input is encountered:

while (i < 100 && (scanf("%d", &a[i])) == 1) { i++; }

First replace "%d" by " %d" this will avoid the new line problems

second if your input contain non numeric input then your while loop will enter in the infinite loop. so you have to check your input if it's a numeric input

The return value of scanf is the number of scanned inputs per call. You can compare it to integer 10 (or '\n'), which would stop the loop when the scanf actually read 10 items. (And to do that, it would have to have ten specifiers in the format string.

You can try

   while((i<10) && (scanf("%d",a+i)==1)) i++;

Accepting any number of arguments has to be programmed eg. as

   while (fgets(mybuf, ALLOCATED_LENGTH-1, stdin)) {
        char *p = mybuf;
        if (*p=='\n') break; // or a better function to test for empty line
        while (custom_scan_next_integer(&p)) i++;
   }

where custom_scan_next_integer modifies the pointer p to forward the proper amount of characters.

You want to do

char discard;

while(i < 100 && (scanf("%d%1[^\n]s", &arr[i], &discard)) == 2)
 i++;

to keep getting input till a new line.

scanf() isn't the best tool for reading entire lines. You should use fgets() to read the line and then parse it using sscanf() or other functions.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!