// ex_ch8_6.c -- menu techniques
// with improved get_first()
#include <stdio.h>
#include <ctype.h>

// prototypes
char get_choice(void);
char get_first(void);
int get_int(void);
void count(void);

int main(void)
{
	int choice;
	void count(void);

	while ((choice = get_choice()) != 'q')
	{
		switch (choice)
		{
		case 'a':
			printf("Buy low, sell high.\n");
			break;
		case 'b':
			// ANSI
			putchar('\a');
			break;
		case 'c':
			count();
			break;
		default:
			printf("Program error\n");
			break;
		}
	}
	printf("Bye.\n");
	return 0;
}

void count(void)
{
	int n, i;
	
	printf("Count how far? Enter an integer: ");
	n = get_int();
	for (i = 1; i <= n; i++)
		printf("%d\n", i);
}

char get_choice(void)
{
	int ch;
	
	printf("Enter the letter of your choice:\n");
	printf("a. advice\t\tb. bell\n"
	       "c. count\t\tq. quit\n");
	ch = get_first();
	while ((ch < 'a' || ch > 'c') && ch != 'q')
	{
		printf("Please respond with a, b, c or q: ");
		ch = get_first();
	}
	return ch;
}

char get_first(void)
{
	int ch;
	// get the first non-newline character, save it in ch
	while ((ch = getchar()) && isspace(ch))
 		continue;
 	
	// skip all the other characters until the newline
	while (getchar() != '\n')
		continue;
	
	// return the first non newline character
	return ch;
}

int get_int(void)
{
	int input;
	char ch;
	
	while (scanf("%d", &input) != 1)
	{
		while ((ch = getchar()) != '\n')
			// dispose of bad input
			putchar(ch);
		printf(" is not an integer.\n"
		       "Please enter an integer value, such as 25, -178, "
		       "or 3: ");
	}
	return input;
}
