Lum – Setting tab width in C++ output in bash

columnsterminaltext formatting

I have a c++ program and I use the tab character "\t" to organize my output to a human-readable columns. However, 8-spaces-wide column in bash is too narrow for me. How can I increase it?

Note: In C++ forums people say: "C++ just outputs the character and is not responsible for the visible output". In linux forums people say: "It is the program you use to output to terminal that is responsible for this, probably less or so."

Best Answer

You can change the tab stops in your terminal using the terminal database, which you can access several ways from C++ (for example, ncurses). You can also access it from shell using tput.

You'd want to start by clearing the tabs (tput tbc). Then move the cursor to each column you want a tab stop in (tput hpa 10 for column 10, for example). Then finally set the tab stop (tput hts). Repeat the positioning and tab setting for each tab stop you want. Example:

echo -e '0\t1\t2\t3\t4\t5\t6\t7\t8'
tput tbc
for ((i=0; i<`tput cols`; i+=10)); do
    tput hpa $i
    tput hts
done
tput hpa 0
echo -e '0\t1\t2\t3\t4\t5\t6\t7\t8'