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.
This question is related to
c
validation
user-input
#include <stdio.h>
main()
{
char str[100];
int num;
while(1) {
printf("Enter a number: ");
scanf("%[^0-9]%d",str,&num);
printf("You entered the number %d\n",num);
}
return 0;
}
%[^0-9]
in scanf()
gobbles up all that is not between 0
and 9
. Basically it cleans the input stream of non-digits and puts it in str
. Well, the length of non-digit sequence is limited to 100. The following %d
selects only integers in the input stream and places it in num
.
You could create a function that reads an integer between 1 and 23 or returns 0 if non-int
e.g.
int getInt()
{
int n = 0;
char buffer[128];
fgets(buffer,sizeof(buffer),stdin);
n = atoi(buffer);
return ( n > 23 || n < 1 ) ? 0 : n;
}
char check1[10], check2[10];
int foo;
do{
printf(">> ");
scanf(" %s", check1);
foo = strtol(check1, NULL, 10); // convert the string to decimal number
sprintf(check2, "%d", foo); // re-convert "foo" to string for comparison
} while (!(strcmp(check1, check2) == 0 && 0 < foo && foo < 24)); // repeat if the input is not number
If the input is number, you can use foo
as your input.
You will need to repeat your call to strtol
inside your loops where you are asking the user to try again. In fact, if you make the loop a do { ... } while(...);
instead of while, you don't get a the same sort of repeat things twice behaviour.
You should also format your code so that it's possible to see where the code is inside a loop and not.
Source: Stackoverflow.com