All wroking fine, too tired to make tests, everything seems fine
This commit is contained in:
129
src/utils.cpp
129
src/utils.cpp
@@ -0,0 +1,129 @@
|
||||
#include "utils.h"
|
||||
#include <limits.h>
|
||||
#include <stdlib.h>
|
||||
#include <errno.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
void clear_screen() {
|
||||
printf("\033[2J\033[H");
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
void wait_enter() {
|
||||
int c;
|
||||
printf("Press Enter to continue...");
|
||||
fflush(stdout);
|
||||
|
||||
while ((c = getchar()) != '\n' && c != EOF) {
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
void sleep_seconds(size_t s) {
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
Sleep(s * 1000);
|
||||
#else
|
||||
// #include <unistd.h>
|
||||
// sleep(s);
|
||||
#endif /* ifdef _WIN32
|
||||
*/
|
||||
}
|
||||
|
||||
void read_string(const char *message, char **dest) {
|
||||
if (!dest) {
|
||||
return;
|
||||
}
|
||||
|
||||
printf("%s", message);
|
||||
|
||||
char buffer[256]; // I mean, should be enough
|
||||
if (!fgets(buffer, sizeof(buffer), stdin))
|
||||
return;
|
||||
|
||||
buffer[strcspn(buffer, "\n")] = '\0';
|
||||
|
||||
char *tmp = static_cast<char *>(malloc(strlen(buffer) + 1));
|
||||
if (!tmp) {
|
||||
return;
|
||||
}
|
||||
|
||||
strcpy(tmp, buffer);
|
||||
|
||||
free(*dest);
|
||||
*dest = tmp;
|
||||
}
|
||||
|
||||
int read_int(const char *message, int *dest) {
|
||||
char buffer[64];
|
||||
char *end;
|
||||
long value;
|
||||
|
||||
printf("%s", message);
|
||||
fflush(stdout);
|
||||
|
||||
if (!fgets(buffer, sizeof(buffer), stdin)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
errno = 0;
|
||||
value = strtol(buffer, &end, 10);
|
||||
|
||||
if (errno != 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (end == buffer) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (*end != '\n' && *end != '\0') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (value < INT_MIN || value > INT_MAX) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
*dest = (int)value;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int read_double(const char *message, double *dest) {
|
||||
char buffer[64];
|
||||
char *end;
|
||||
double value;
|
||||
|
||||
printf("%s", message);
|
||||
fflush(stdout);
|
||||
|
||||
if (!fgets(buffer, sizeof(buffer), stdin)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
errno = 0;
|
||||
value = strtod(buffer, &end);
|
||||
|
||||
if (errno != 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (end == buffer) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (*end != '\n' && *end != '\0') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!isfinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
*dest = value;
|
||||
return 1;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user