Accepting any number of inputs from scanf function

2020-03-04 07:19发布

I am trying to read an unknown number of inputs using scanf function.

int a[100];
int i = 0;

while((scanf("%d", &a[i])) != '\n')
 i++;

// Next part of the code

But this function is not going to next part of the code, seems like there is an infinite while loop.

How Do I solve this logical error? Is there any other alternatives to scanf like sscanf to read integers into an array?

5条回答
Ridiculous、
2楼-- · 2020-03-04 07:58

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).

查看更多
Evening l夕情丶
3楼-- · 2020-03-04 07:59

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.

查看更多
淡お忘
4楼-- · 2020-03-04 08:07

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++; }
查看更多
别忘想泡老子
5楼-- · 2020-03-04 08:16

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.

查看更多
家丑人穷心不美
6楼-- · 2020-03-04 08:17

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

查看更多
登录 后发表回答