Here is some C code trying simply to prevent the user from typing a character or an integer less than 0 or more than 23.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *input;
char *iPtr;
int count = 0;
int rows;
printf("Enter an integer: ");
scanf("%s", input);
rows = strtol(input, &iPtr, 0);
while( *iPtr != '\0') // Check if any character has been inserted
{
printf("Enter an integer between 1 and 23: ");
scanf("%s", input);
}
while(0 < rows && rows < 24) // check if the user input is within the boundaries
{
printf("Select an integer from 1 to 23: ");
scanf("%s", input);
}
while (count != rows)
{
/* Do some stuff */
}
return 0;
}
I made it halfway through and a small push up will be appreciated.
Use
scanf("%d",&rows)instead ofscanf("%s",input)This allow you to get direcly the integer value from stdin without need to convert to int.
If the user enter a string containing a non numeric characters then you have to clean your stdin before the next
scanf("%d",&rows).your code could look like this:
Explanation
1)
This means expecting from the user input an integer and close to it a non numeric character.
Example1: If the user enter
aaddkand thenENTER, the scanf will return 0. Nothing captedExample2: If the user enter
45and thenENTER, the scanf will return 2 (2 elements are capted). Here%dis capting45and%cis capting\nExample3: If the user enter
45aaaddand thenENTER, the scanf will return 2 (2 elements are capted). Here%dis capting45and%cis captinga2)
In the example1: this condition is
TRUEbecause scanf return0(!=2)In the example2: this condition is
FALSEbecause scanf return2andc == '\n'In the example3: this condition is
TRUEbecause scanf return2andc == 'a' (!='\n')3)
clean_stdin()is alwaysTRUEbecause the function return always1In the example1: The
(scanf("%d%c", &rows, &c)!=2 || c!='\n')isTRUEso the condition after the&&should be checked so theclean_stdin()will be executed and the whole condition isTRUEIn the example2: The
(scanf("%d%c", &rows, &c)!=2 || c!='\n')isFALSEso the condition after the&&will not checked (because what ever its result is the whole condition will beFALSE) so theclean_stdin()will not be executed and the whole condition isFALSEIn the example3: The
(scanf("%d%c", &rows, &c)!=2 || c!='\n')isTRUEso the condition after the&&should be checked so theclean_stdin()will be executed and the whole condition isTRUESo you can remark that
clean_stdin()will be executed only if the user enter a string containing non numeric character.And this condition
((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin())will returnFALSEonly if the user enter anintegerand nothing elseAnd if the condition
((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin())isFALSEand theintegeris between and1and23then thewhileloop will break else thewhileloop will continue