0

Possible Duplicate:
C++ alignment when printing cout <<

I am writing a set of words in an output file . I have left three tabspaces using '\t' character between the words . But at times when the words are too small or too large there seems to be a problem with the alignment. How to give a constant space between words which would work even when the words are small ?

Here's what i am talking about.

    Word:elpmas         Count:1
    Word:This           Count:4
    Word:pmasel         Count:1
    Word:is         Count:1
    Word:sample         Count:1
    Word:sentence           Count:1
    Word:si         Count:1
    Word:a          Count:1

I want to have a constant space between the words and the counts. I currently use

cout<< "Word:"<< hash->key <<"\t\t\t" << "Count:" << hash->value <<endl;

Help me out.

Community
  • 1
  • 1
Pradep
  • 1,874
  • 5
  • 21
  • 31

2 Answers2

5

The setw stream manipulator is useful for aligning columns in tabular output. For instance,

cout << "Word:" << setw(15) << hash->key << " Count:" << hash->value << endl;

Will properly align your output provided that your keys are at most 15 characters.

meastham
  • 146
  • 2
1

A tab moves to specific 'fixed column' positions. Your tabs look like 4 characters tab-stops

Depending on where you are when you print a tab, it will be anything from 1 to 4 characters to the next tab column.

So you need to keep track (or calculate) the current position before printing the tab. In your case, it looks like every line starts with 'Word:' which leaves three characters to the tab column. So if a word is less than three characters, it needs an 'extra tab'.

Also if a word is longer than (3+4) 7 characters, you need to put out one less tab.

Summary, if you want to control layout with your code, by using tabs, you will need to use a variable number depending on the word width.

gbulmer
  • 4,210
  • 18
  • 20