Last active
November 18, 2023 21:10
-
-
Save jimdiroffii/a98fed43c65f21087cd352f4aeaf4027 to your computer and use it in GitHub Desktop.
Center text in a fixed-width field using C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "C:\gsl\narrow" // path to GSL include files | |
#include <string> | |
/*** | |
* Center text in a fixed-width field | |
* https://stackoverflow.com/questions/14861018/center-text-in-fixed-width-field-with-stream-manipulators-in-c | |
*/ | |
std::string center(const std::string& text, int width) | |
{ | |
/*** | |
* FIX: fixed-size type, uint64_t, resolves C4365, type mismatch with reserve and append | |
* FIX: gsl::narrow_cast resolves warning about unsafe static_cast usage, requires GSL library | |
*/ | |
const uint64_t len = gsl::narrow_cast<uint64_t>(text.length()); | |
// const uint64_t len = static_cast<uint64_t>(text.length()); | |
const uint64_t padding = width - len; | |
const uint64_t paddingLeft = padding / 2; | |
const uint64_t paddingRight = padding - paddingLeft; | |
std::string result; | |
result.reserve(static_cast<uint64_t>(width)); | |
result.append(paddingLeft, ' '); | |
result.append(text); | |
result.append(paddingRight, ' '); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment