Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / Center text in fixed-width field with stream manipulators in C++

Center text in fixed-width field with stream manipulators in C++

August 20, 2021 by James Palmer

In C++20 you’ll be able to use std::format to do this:
outputStream << std::format("|{:^10}|{:^10}|{:^9}|n", "Table", "Column", "Header"); Output: | Table | Column | Header | In the meantime you can use the {fmt} library, std::format is based on. {fmt} also provides the print function that makes this even easier and more efficient (godbolt): fmt::print("|{:^10}|{:^10}|{:^9}|n", "Table", "Column", "Header"); Disclaimer: I'm the author of {fmt} and C++20 std::format. Here's a helper class that accomplish what you want: #include
#include
#include

template >
class center_helper {
std::basic_string str_;
public:
center_helper(std::basic_string str) : str_(str) {}
template
friend std::basic_ostream& operator<<(std::basic_ostream& s, const center_helper& c);
};

template >
center_helper centered(std::basic_string str) {
return center_helper(str);
}

// redeclare for std::string directly so we can support anything that implicitly converts to std::string
center_helper centered(const std::string& str) {
return center_helper(str);
}

template
std::basic_ostream& operator<<(std::basic_ostream& s, const center_helper& c) {
std::streamsize w = s.width();
if (w > c.str_.length()) {
std::streamsize left = (w + c.str_.length()) / 2;
s.width(left);
s << c.str_; s.width(w - left); s << ""; } else { s << c.str_; } return s; } It's used simply by calling centered("String"), like so: int main(int argc, char *argv[]) { std::cout << "|" << std::setw(10) << centered("Table") << "|" << std::setw(10) << centered("Column") << "|" << std::setw(9) << centered("Header") << "|" << std::endl; }

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in