Skip to content

Instantly share code, notes, and snippets.

@nevack
Last active May 30, 2022 19:15
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nevack/4b4a36aaac93c4274b03f017277a9a94 to your computer and use it in GitHub Desktop.
Save nevack/4b4a36aaac93c4274b03f017277a9a94 to your computer and use it in GitHub Desktop.
Reading Numbers in C
#include <stdio.h>
int ReadInteger() {
int number;
char c;
while (1) {
// Read token token from stdout, ended by newline
if (!scanf_s("%d", &number) || getchar() != '\n') {
// Clear stdout before reading next token
while ((c = getchar()) != '\n' && c != EOF);
} else {
return number;
}
printf_s("Incorrect number.\nTry again: ");
}
}
// Use setlocale(LC_NUMERIC, "C") for period delimeter.
double ReadDouble() {
double number;
char c;
while (1) {
if (!scanf_s("%lf", &number) || getchar() != '\n') {
while ((c = getchar()) != '\n' && c != EOF);
} else {
return number;
}
printf_s("Incorrect number.\nTry again: ");
}
}
long ReadTime() {
int hours, minutes;
char c;
while (1) {
if (scanf_s("%d:%d", &hours, &minutes) < 2 || getchar() != '\n') {
while ((c = getchar()) != '\n' && c != EOF);
} else if (hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59) {
return hours * 60 + minutes;
}
printf_s("Time should be in HH:MM fromat.\nTry again: ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment