The name of printChart()
misled me for a while. Its purpose is to print a single line of the chart, so perhaps it should be called printLine()
(or even createLine()
or similar, if you accept Carcigenicate's suggestion). Good names make a huge difference in the comprehension of your code, but inventing them is one of the hardest problems in programming!
Inside the function, there's std::string ws
that is constructed on every call, whether it's used or not, and always with the same contents. This is obviously wasteful. One way to reduce the overhead is to to make it static
so that it's only initialised once - it's worth making it const
as well so you can be sure its value never changes:
static const std::string ws = "White Space";
Looking at how we use it (streaming it to output), there's no benefit to std::string
over an ordinary (null-terminated, C-style) string:
static const char *const ws = "White Space";
(The two appearances of const
on different sides of the *
indicate that this is a constant pointer to constant characters - you can't modify ws
and you can't modify ws[i]
).
Alternatively, as an array:
static const char ws[] = "White Space";
We can also reduce its scope, as it's used only in a small part of the code:
if (isspace(code)) {
static const char ws[] = "White Space";
std::cout << ws << "\n";
} else {
std::cout << symbol << "\n";
}
At this point, it's probably clearer to inline the one and only use, and not give it a separate name:
if (isspace(code)) {
std::cout << "White Space\n";
} else {
std::cout << symbol << "\n";
}
(I agree with most of the suggestions in other answers; no need to duplicate them here).
char
values and the printable characters, and expects you to do any necessary conversions. This can be a complex area, and soon gets well out of beginner territory, so let's assume that the host environment uses ASCII. \$\endgroup\$char
type) to represent strings as a sequence of Unicode characters, and to convert between that and UTF-8 or UTF-16 for its I/O. You're right that a sequence of UTF-8 bytes is also an ASCII-compatible form. \$\endgroup\$