Last active
May 30, 2022 19:15
-
-
Save nevack/4b4a36aaac93c4274b03f017277a9a94 to your computer and use it in GitHub Desktop.
Reading Numbers in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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