Skip to content

Instantly share code, notes, and snippets.

@yves-chevallier
Created November 18, 2019 08:54
Show Gist options
  • Save yves-chevallier/11f48edc68aef80708c94fa7a4b47f6a to your computer and use it in GitHub Desktop.
Save yves-chevallier/11f48edc68aef80708c94fa7a4b47f6a to your computer and use it in GitHub Desktop.
Menu en C
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <ctype.h>
void q(void) {
char d;
if(scanf("%hhd", &d)) {
printf("Info: Scanf got %hhd\n", d);
} else {
printf("Error: Scanf failed");
}
}
bool do_continue(void) {
for(;;) {
printf("\nDo you want to continue? [yN]: ");
char c;
while (scanf("%c", &c) > 0) {
switch(tolower(c)) {
case 'y':
return true;
case 'n':
return false;
}
}
}
}
int main(void)
{
bool is_interactive = isatty(fileno(stdin));
char c;
if (is_interactive) printf("Interactive mode\n");
while ((c = getchar()) != EOF) {
if (isspace(c)) {
printf("Info: Ignoring 0x%02hhx\n", c);
continue;
}
scanf("%*[\t ]");
if (is_interactive && getchar() != '\n') {
scanf("%*[^\n]");
scanf("%*1[\n]");
printf("Error: Wrong value!\n");
continue;
}
printf("Info: Got 0x%02hhx\n", c);
switch(c) {
case 'q':
do {
q();
} while(do_continue());
break;
case '0':
printf("Info: Exit with zero\n");
exit(EXIT_SUCCESS);
break;
}
}
printf("Info: Exit with EOF\n");
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment