-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray_enumeration.cpp
More file actions
83 lines (69 loc) · 2.41 KB
/
array_enumeration.cpp
File metadata and controls
83 lines (69 loc) · 2.41 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
#include "diy.h"
#include <vector>
#include <functional>
namespace Color
{
enum Type
{
none,
black,
red,
green,
blue,
cyan,
max_colortypes
};
using namespace std::literals;
constexpr std::array colorName{"None"sv,"Black"sv, "Red"sv, "Green"sv,"Blue"sv, "Cyan"sv};
constexpr std::array colorArray{black, red, green, blue, cyan};
static_assert(colorName.size() == max_colortypes && "Type Number calculation Error here!\n"); // Align the lengths on enumeration and NameArray
}
constexpr std::string_view getColorName(const Color::Type type)
{
return Color::colorName[static_cast<std::size_t>(type)];
}
std::ostream& operator<<(std::ostream& out, Color::Type type) // enumerator -> stringview
{
return out << getColorName(type);
}
constexpr void capitialize(std::string& str)
{
for(char& character:str)
character = static_cast<char>(tolower(static_cast<unsigned char>(character)));
str[0] = static_cast<char>(toupper(static_cast<unsigned char>(str[0])));
}
// Overwrite cin
// Color::Types type{};
// std::cin >> type;
std::istream& operator>>(std::istream& in, Color::Type& type) // string -> enumerator
{
std::string input{};
std::getline(in >> std::ws, input); // skip all the whitespace before the valid context and drop the vaild context to string `input`
capitialize(input);
for (std::size_t index{0}; index < Color::max_colortypes; ++index)
{
if(input == Color::colorName[index])
{
type = static_cast<Color::Type>(index);
return in;
}
}
// if no match, set cin's state as Failed
in.setstate(std::ios_base::failbit);
type = {}; // we just value-initialize it for the failure situation
return in; // then we return the os' input component back
}
int main()
{
// Color::Type type{};
// std::cout << "Please enter Your favoriate color: ";
// std::cin >> type;
// if (std::cin) // if user's input is matched with Color::type
// std::cout << "Oh! " << type << " is my favorate too!\n";
// else
// std::cout << "You just input an invalid Color.\n";
for(const auto color:Color::colorArray) // compiler is incapable to traversal a numeration but array<numerator> is fine
std::cout << color << ' ';
std::cout << '\n';
return 0;
}