0

I want to format a grid nicely. It is 9x9 grid. I want to delimit it

after every 3rd column - put "*"

else - '\t'.

after every 3rd row put "-------------------------"

Horizontal line works nicely - this is easy.

But in column 3 it starts printing only 2-3 spaces instead of '\t'.

The code:

  static int grid[9][9] ;

void print_grid(){
     cout << "PRINTING GRID" <<endl ;
     for(int row = 0 ; row < 9 ; row++){
            for(int column = 0 ; column < 9 ; column++){
                    if(column > 0 && (column + 1) % 3 == 0 && (column + 1) != 9 )
                          cout <<grid[row][column] << " * " ;
             else    cout  <<grid[row][column]  <<"\t" ;                                                           
                    }
                    if( (row+1) % 3 == 0){cout <<endl ; 
                      cout << "---------------------------------------------------------------------" <<endl ;}
                    else  cout <<endl <<endl ;                    
            }

     }

int main(){
     print_grid() ;   
    return 0 ;         
    }

table

My question is: in the red area why does it print 2-3 spaces instead of "\t" ? why does '\t' change its length??

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ERJAN
  • 23,696
  • 23
  • 72
  • 146

3 Answers3

1

The tab key doesn't have a certain length, all it does is advanced the cursor to the next stop in the document.

The length of the distance between stops can vary from system to system.

Caesar
  • 9,483
  • 8
  • 40
  • 66
  • omg, i just changed "\t" to " " - 3 spaces, and it looks nice! – ERJAN Jan 25 '14 at 15:03
  • so i should learn the details of the language - because you can spend time looking for a bug - where this is just me not knowing the details. – ERJAN Jan 25 '14 at 16:25
1

Your code is fine. It's just the way tabs work in the console, they go to next tab stop which will be very 8 characters. If there are 5 characters already since last tab stop, it will only advance 3 characters.

You can check you get similar results by just using echo

echo -e "X\tX\nXXXXX\tX"
X       X
XXXXX   X

You can use two consecutive tabs if you want more space. If you want more control on alignment than that, you can stop using tabs and try using std::setw instead.

toth
  • 2,519
  • 1
  • 15
  • 23
1

You really don't want tab here you want to use iostream alignment manipulators.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54