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?
Inputting Multiple ValuesIf you have multiple format specifiers within the string argument of scanf, you can input multiple values. All you need to do is to separate each format specifier with a DELIMITER - a string that separates variables.
scanf("%d", &b); The program will read in an integer value that the user enters on the keyboard (%d is for integers, as is printf, so b must be declared as an int) and place that value into b. The scanf function uses the same placeholders as printf: int uses %d.
The scanf() function reads data from the standard input stream stdin into the locations given by each entry in argument-list. Each argument must be a pointer to a variable with a type that corresponds to a type specifier in format-string.
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++; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With