Jump to content


Check out our Community Blogs

TC_EX

Member Since 28 Dec 2010
Offline Last Active Dec 29 2010 06:01 AM
-----

Posts I've Made

In Topic: [C] Validating user input...

28 December 2010 - 10:58 PM

Try this on for size. You needn't use enter when entering double digits and if you want to report an error, fine, but app will ignore non-digits.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <time.h>

int ReadInput () {
	char Entry [16];
  int Numb, Pos = 0, Ch;

	while ((Ch = getch ()) != 13) {
		if (Ch < '0' || Ch > '9')
			continue;

		putch (Ch);
		Entry [Pos++] = Ch;
		if (Pos == 2)
			break;
		}

	Entry [Pos] = NULL;
	return atoi(Entry);
	}

int main (int argc, const char * argv[]) {
	int ranNum, UserGuess, Guesses = 0;
  char choice = 'N';

	do {
		Guesses = 0;
		srand (time (NULL));
		ranNum = rand () % 100;

		printf ("\n\nHi/Low Game\n\n\n\n");

		do {
			printf ("%d ", ++Guesses);
			UserGuess = ReadInput ();
			printf ("    ->");

			if (UserGuess == ranNum)
				break;

			if (UserGuess < ranNum)
				printf ("LOW");
			else
				printf ("HIGH");

			printf ("\n");

			} while (1);

		printf ("\n\nCongratulations  Play again? [Y/N]");
		choice = getch ();

		} while (choice == 'Y' || choice == 'y');


	return 0;
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download