-
Notifications
You must be signed in to change notification settings - Fork 0
/
center.cpp
37 lines (33 loc) · 1.29 KB
/
center.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
// https://stackoverflow.com/questions/14861018/center-text-in-fixed-width-field-with-stream-manipulators-in-c/14861289#14861289
#include <string>
#include <iostream>
#include <iomanip>
template<typename charT, typename traits = std::char_traits<charT> >
class center_helper {
std::basic_string<charT, traits> str_;
public:
center_helper(std::basic_string<charT, traits> str) : str_(str) {}
template<typename a, typename b>
friend std::basic_ostream<a, b>& operator<<(std::basic_ostream<a, b>& s, const center_helper<a, b>& c);
};
template<typename charT, typename traits = std::char_traits<charT> >
center_helper<charT, traits> centered(std::basic_string<charT, traits> str) {
return center_helper<charT, traits>(str);
}
center_helper<std::string::value_type, std::string::traits_type> centered(const std::string& str) {
return center_helper<std::string::value_type, std::string::traits_type>(str);
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& s, const center_helper<charT, traits>& 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;
}