I was working on the same thing. I tried isdigit and couldnt seem to get the logic quite right. Thanks to your advice, I solved my problem this way:
Code:
#include <stdio.h>
#include <ctype.h>
#define MAXLINE 12
int get_int(int *result)
{
char c, line [MAXLINE]; // Initialize function variables
printf("Input a positive integer with a maximum of %d digits: ",MAXLINE);
return fgets(line, MAXLINE, stdin) && !isspace(*line) && //uses fgets to return only a positive integer
sscanf(line, "%d%c", result, &c) == 2 && (c == '\n' || c == '\0') &&
*result >= 0;
}
int main(void)
{
int n; //Initlaizes the n variable
//SELF DOCUMENTATION BEGIN
printf("This program will take a line from the keyboard \nand print ONLY if the input is a valid positive integer.\n\n");
//SELF DOCUMENTATION END
while( !get_int(&n)){ // While function get_int does not equal a positive integer
fputs("\nERROR: DO IT AGAIN!\n\n", stdout);// Looping printed error message
fflush(stdout);}
printf("Your positive integer is: %d\n", n);
return 0;
}