-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.cpp
More file actions
101 lines (85 loc) · 2.48 KB
/
Utils.cpp
File metadata and controls
101 lines (85 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include "Utils.h"
#include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
namespace {
bool isValidName(const std::string& name) {
if (name.empty()) {
return false;
}
return std::all_of(name.begin(), name.end(), [](unsigned char ch) {
return std::isalnum(ch) || ch == '_' || ch == '-';
});
}
}
namespace Utils {
void clearInput() {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
int readIntInRange(const std::string& prompt, int low, int high) {
int value = 0;
while (true) {
std::cout << prompt;
if (std::cin >> value && value >= low && value <= high) {
clearInput();
return value;
}
std::cout << color("Invalid choice. Enter a number from " + std::to_string(low)
+ " to " + std::to_string(high) + ".\n", "31");
clearInput();
}
}
double readPositiveAmount(const std::string& prompt) {
double value = 0.0;
while (true) {
std::cout << prompt;
if (std::cin >> value && value > 0.0) {
clearInput();
return value;
}
std::cout << color("Invalid amount. Enter a positive number.\n", "31");
clearInput();
}
}
std::string readName(const std::string& prompt) {
std::string name;
while (true) {
std::cout << prompt;
std::getline(std::cin, name);
if (isValidName(name)) {
return name;
}
std::cout << color("Invalid name. Use letters, digits, '_' or '-' only.\n", "31");
}
}
std::string formatMoney(double amount) {
std::ostringstream out;
out << std::fixed << std::setprecision(2) << amount;
return out.str();
}
void printLine(char ch, int width) {
std::cout << std::string(width, ch) << '\n';
}
bool colorsEnabled() {
#ifdef _WIN32
return _isatty(_fileno(stdout)) != 0;
#else
return isatty(fileno(stdout)) != 0;
#endif
}
std::string color(const std::string& text, const std::string& code) {
if (!colorsEnabled()) {
return text;
}
return "\033[" + code + "m" + text + "\033[0m";
}
}