-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.cpp
109 lines (95 loc) · 2.42 KB
/
Utils.cpp
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
102
103
104
105
106
107
108
109
#include <algorithm>
#include <fstream>
#include <iostream>
#include <optional>
#include "Utils.h"
namespace fs
{
std::string Utils::trim(const std::string& str, const std::string& whitespace)
{
const auto strBegin = str.find_first_not_of(whitespace);
if (strBegin == std::string::npos)
{
return "";
}
const auto strEnd = str.find_last_not_of(whitespace);
const auto strRange = strEnd - strBegin + 1;
return str.substr(strBegin, strRange);
}
bool Utils::areAllCharactersAlpha(const std::string& str)
{
return std::all_of(str.begin(), str.end(), [](const char& c)
{
return std::isalpha(c);
});
}
std::optional<int> Utils::getNumber()
{
int number;
std::cin >> number;
char nextChar;
while (std::cin.get(nextChar))
{
if (nextChar == '\n') break;
if (!isspace(nextChar))
{
std::cin.setstate(std::ios_base::failbit);
break;
}
}
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input. Please enter a number.\n";
return {};
}
return { number };
}
std::optional<std::string> Utils::getLine()
{
std::string buff{};
std::getline(std::cin, buff);
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::clog << "ERROR: Utils::getLine() \n\n";
return {};
}
return { buff };
}
void Utils::bufferSafetyCheck()
{
if (std::cin.rdbuf()->in_avail() > 0)
{
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::clog << "ERROR: Utils::bufferSafetyCheck() \n\n";
}
}
bool Utils::promptToExitLoop()
{
std::cout << "Do you want to cancel this operation? (y/N): ";
std::string buff;
std::getline(std::cin, buff);
return buff == "y" || buff == "Y";
}
bool Utils::checkIfDirectoryExists(const std::filesystem::path& dir)
{
return std::filesystem::exists(dir);
}
bool Utils::createDirectory(const std::filesystem::path& dir)
{
return std::filesystem::create_directory(dir);
}
bool Utils::createFile(const std::filesystem::path& file)
{
std::ofstream f{ file };
f << "";
return true;
}
bool Utils::removeFile(const std::filesystem::path& file)
{
return std::filesystem::remove(file);
}
} // namespace fs