interpim wrote:
ok the function is supposed to accept only non-negative integers...
but it still accepts letters input through the function. Such as
'23e' still passes through. I tried to use isalpha in the or
statement to cause an error, but it causes an error for everything
input. How do I make an error occur when anything other than
numbers are put in?
#include <stdio.h>
#define MAXLINE 20
int main(void)
{
char line[MAXLINE];
int error,n;
do{
printf("Input a positive integer: ");
fgets(line, MAXLINE, stdin);
error=sscanf(line, "%d",&n) !=1||n<=0;
if (error)
printf("\nERROR: Do it again.\n");
} while(error);
}
Please fix your line length. It should never exceed 80, and 65 is
about optimum.
Look up the %n specifier, which will show where the conversion
stopped. You can then examine the remainder of the input string,
to see if it consists of anything other than white space, and
object if desired. From N869:
n No input is consumed. The corresponding argument
shall be a pointer to signed integer into which is
to be written the number of characters read from the
input stream so far by this call to the fscanf
function. Execution of a %n directive does not
increment the assignment count returned at the
completion of execution of the fscanf function. No
argument is converted, but one is consumed. If the
conversion specification includes an assignment-
suppressing character or a field width, the behavior
is undefined.
An alternative is to use strtol(), which can also return a pointer
past the converted value, and is probably clearer. I am not sure
whether or not strtoul() will object to a leading - sign, or
simply do the unsigned modulo operations. At any rate using
either also allows you to put firm limitations on the input range.
--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!