I am writing a simple program in C that allows the user to view the contents of a txt file.
I want to resrict the input the user can make... e.g only keys 1-5 and nothing else....
How is this possible?
Thanks
Tom
Printable View
I am writing a simple program in C that allows the user to view the contents of a txt file.
I want to resrict the input the user can make... e.g only keys 1-5 and nothing else....
How is this possible?
Thanks
Tom
That will be OS specific.
For Windows/DOS, use getch().
Read this thread for a simple example of using getch() to accomplish custom input.
gg
>I want to resrict the input the user can make... e.g only keys 1-5 and nothing else....
You can easily restrict the input that your program accepts, but actually restricting the user from giving you more than you want is not a trivial task, and there's no way to do it within the confines of standard C.
The former is simple:
Code:int inrange ( int val, int low, int high )
{
return val >= low && high >= val;
}
...
/* Get input from user */
if ( inrange ( input, 1, 5 ) ) {
/* It's good */
}
else
/* Handle erroneous input */
thanks all
Tom
Ye could also try:
Code:scanf("%[1-5]", &reciving array);
out of curiosity, could something like this do?
Code:#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int range;
char buf[10], *p;
for(;;)
{
printf("Enter your number: ");
fgets(buf, sizeof(buf), stdin);
if((range = (int)strtol(buf, &p, 10)) >=1 && range <= 5)
break;
printf("\nYou are not authorized for that input. Try again\n");
}
printf("\noption = %d", range);
while(getchar() != '\n');
return 0;
}
this is pretty cryptic is it written out like this?Code:return val >= low && high >= val;
I was just wondering I have never seen something like that.Code:if(val>=low && high >= val){
return val;
}
My brother says that it returns either 1 or 0. Just wondering.
>>this is pretty cryptic is it written out like this?
That line of code simply(!) performs two tests, and the result is returned in the form of 1 or 0. Simply put, it returns 1 (true) if the number is within a given range, 0 (false) if not.
Your suggestion of writing "return val;" brings a new meaning to the code, that doesn't give the same result.
>this is pretty cryptic
Only if you aren't used to seeing somebody return the result of a boolean expression. You can lengthen it to something (debatably) more transparent like so:
>My brother says that it returns either 1 or 0.Code:int inrange ( int val, int low, int high )
{
if ( val >= low && high >= val )
return 1;
else
return 0;
}
Your brother would be correct. Any boolean expression returns 1 for true and 0 for false.