How to determine the (printed) length of a std::string with tab characters expanded?
Given a C++ std::string variable which includes tab characters, is it possible to determine the length of that string as it would appear on the "screen"? i.e.:
std::string var = "\t\t\t"; std::cout << var.length(); // result: 3 std::cout << printed_length(var); // result: 3*(# of spaces per tab)
Not easily. It's impossible without specific knowledge of the "screen" involved (really, the software driving the output), because tab expansion varies so widely. There are four fairly obvious possibilities, based on fixed expansion vs. expansion to a multiple of something, and based on character cells vs. some other fixed measurement (e.g., for proportional fonts). There are also "smart tabs" with even more complex criteria, where one tab's expansion may depend upon another tab.
On a typical "console" that'll be expansion mod 8 character cells. To deal with that, you'll not only have to count the tabs, but also look at the position of each tab in the string. You'll also have to make some assumptions (or provide a parameter) about the position of the beginning of the string relative to a tab stop.
Bottom line: if you want to do something like this, you'll have to do it yourself, based on knowledge of how tabs will be expanded on your target.
We'll make the simplifying assumption that the text in the string is the only text on a line, or that it starts on a tab boundary.
Each tab character will expand to a different number of spaces based on the number of characters prior to it.
expansion_count = n_spaces - (current_count % n_spaces);