Daniel Toh Daniel Toh - 12 days ago 4
C Question

how to stop scanning when input is null (scan an unknown number of ints)

I'm currently working on a program that scans each int and finds out if it is perfect or not. The problem is, I do not know how many ints there are in the input, so I want to find out how to stop scanning when the input ends.

Code:

#include <stdio.h>
int main(){
int input[500], count;
for (count = 0; count < 500; count++){
scanf("%d",&input[count]);
if (input[count] == 0)
break;
}

for (count = 0; count < 500 ;count++){
if (findFactors(input[count]) % input[count] == 0)
printf("%d perfect\n",input[count]);

else
if (findFactors(input[count]) % input[count] <= 2 || findFactors(input[count]) % input[count] >= input[count]-2)
printf("%d almost perfect\n",input[count]);

else printf("%d not perfect\n",input[count]);
}


In this case, I need to enter 500 numbers for the code to run. I need it to run when the input is null. I know there is '/0' or something but I don't know how to use it in this code.
}

Answer

When you use a function read the doc

In return value

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

So you need to check the return value of scanf:

if (scanf("%d", &input[count]) != 1)
  break;
Comments