Skip to content

Instantly share code, notes, and snippets.

@pauldwhitman
Last active December 14, 2015 17:39
Show Gist options
  • Save pauldwhitman/5123648 to your computer and use it in GitHub Desktop.
Save pauldwhitman/5123648 to your computer and use it in GitHub Desktop.
Part of the "Chess in C" blog post series. Asking the user for the row and column of a chess piece. Intentionally contains a bug where the second question is asked even if the first question hasn't been answered correctly.
/* Print and ask for the row number */
printf("\nRow? (0..7): ");
/* Get some input */
if (fgets(input, sizeof(input), stdin)) {
/* Make sure it's a number! */
if (sscanf(input, "%d", &pieceRow)) {
/* Make sure it's between 0 and 7! */
if (pieceRow >= 0 && pieceRow <= 7) {
/* If you got here, congratulations. It's valid input. */
printf("You've entered %i", pieceRow);
} else {
/* It wasn't between 0 and 7! */
printf("ERROR: Not between 0 and 7");
}
} else {
/* It wasn't a number! */
printf("ERROR: Not a number");
}
}
/* Print and ask for the column number */
printf("\nColumn? (0..7): ");
/* Get some input */
if (fgets(input, sizeof(input), stdin)) {
/* Make sure it's a number! */
if (sscanf(input, "%i", &pieceColumn)) {
/* Make sure it's between 0 and 7! */
if (pieceColumn >= 0 && pieceColumn <= 7) {
/* If you got here, congratulations. It's valid input. */
printf("You've entered %i", pieceColumn);
} else {
/* It wasn't between 0 and 7! */
printf("ERROR: Not between 0 and 7");
}
} else {
/* It wasn't a number! */
printf("ERROR: Not a number");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment