// ex_ch8_8.c
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

// prototypes
char get_selection();
char get_first();
float get_number();

int main(void)
{
	char selection, op;
	float first, second, result;
	
	while ((selection = get_selection()) != 'q')
	{
		switch (selection)
		{
		case 'a':
			op = '+';
			break;
		case 's':
			op = '-';
			break;
		case 'm':
			op = '*';
			break;
		case 'd':
			op = '/';
			break;
		}
		printf("Enter first number: ");
		first = get_number();
		while (true)
		{
			printf("Enter second number: ");
			second = get_number();
			if (op != '/')
				break;
			if (second == 0.0)
				printf("Enter a number other than zero!\n");
			else
				break;
		}

		// calculate now
		switch (op)
		{
		case '+':
			result = first + second;
			break;
		case '-':
			result = first - second;
			break;
		case '*':
			result = first * second;
			break;
		case '/':
			result = first / second;
			break;
		}
		printf("%.2f %c %.2f = %.2f\n", first, op, second, result);
	}
	return 0;
}

float get_number(void)
{
	float input;
	char ch;
	
	while (scanf("%f", &input) != 1)
	{
		while ((ch = getchar()) != '\n')
			// dispose of bad input
			putchar(ch);
		printf(" is not a number.\n"
		       "Please enter a number, such as 2.5, -1.78E8, "
		       "or 3: ");
	}
	return input;
}

char get_selection(void)
{
	char ch;
	printf("Enter the operation of your choice\n"
	       "a. add\t\ts. subtract\n"
	       "m. multiply\td. divide\n"
	       "q. quit\n");
		
	while ((ch = get_first()))
	{
		if (ch == 'a' || ch == 's' || ch == 'm' || ch == 'd'
		    || ch == 'q')
			return ch;
		else
		{
			printf("%c is invalid, enter something useful\n", ch);
			printf("Enter the operation of your choice\n"
			       "a. add\t\ts. subtract\n"
			       "m. multiply\td. divide\n"
			       "q. quit\n");
		}
	}
	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;
}

