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?
scanf
returns the number of input items that have been successfully matched and assigned, thus it is reasonable to do:Now you want to be able to read multiple numbers, each defined on the new line. Then you could simply do this:
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 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
Accepting any number of arguments has to be programmed eg. as
where
custom_scan_next_integer
modifies the pointer p to forward the proper amount of characters.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:
You want to do
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.
First replace
"%d"
by" %d"
this will avoid the new line problemssecond 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