Last active
December 15, 2015 11:09
-
-
Save maxdeliso/5251112 to your computer and use it in GitHub Desktop.
example of function pointers and safe terminal mode input in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * example of function pointers and safe terminal mode input in C | |
| */ | |
| #include <stdarg.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <stdbool.h> | |
| typedef void (*printFunc_t) (void); | |
| void firstPit(); | |
| void secondPit(); | |
| void thirdPit(); | |
| int main() { | |
| printFunc_t funcArray[] = {firstPit, secondPit, thirdPit}; | |
| int userNum = 0; | |
| bool userNumValid = false; | |
| int ret; | |
| do { | |
| printf("enter a number, 1-3\n"); | |
| if( (ret = fscanf(stdin, "%i", &userNum)) != 1 ) { | |
| while( !feof(stdin) && (ret = getc(stdin)) != '\n' ); | |
| } else { | |
| userNumValid = (userNum >= 1 && userNum <= 3); | |
| } | |
| } while(!feof(stdin) && !userNumValid); | |
| if(userNumValid) { | |
| funcArray[userNum - 1] (); | |
| } | |
| return EXIT_SUCCESS; | |
| } | |
| void firstPit() { | |
| printf("you selected 1\n"); | |
| } | |
| void secondPit() { | |
| printf("you selected 2\n"); | |
| } | |
| void thirdPit() { | |
| printf("you selected 3\n"); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment