user2147954 user2147954 - 4 years ago 81
C Question

Accepting any number of inputs from scanf function

I am trying to read an unknown number of inputs using

scanf
function.

int array[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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download