Skip to content

Instantly share code, notes, and snippets.

@maxdeliso
Last active December 15, 2015 11:09
Show Gist options
  • Save maxdeliso/5251112 to your computer and use it in GitHub Desktop.
Save maxdeliso/5251112 to your computer and use it in GitHub Desktop.
example of function pointers and safe terminal mode input in C
/*
* 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