\t giving more space in c++

Why is the output showing more space between the words "10 years" and "15 years" despite giving only single \t as between other words.


1
2
3
4
5
6
7
8
#include<iostream>
using namespace std;
int main()
{
float P =1000, r1 =5;
cout<<"Rate of"<<"\t"<<"Initial Amount"<<"\t"<<"5 Years"<<"\t"<<"10 Years"<<"\t"<<"15 Years"<<"\n";
return 0;
}

Last edited on
closed account (48T7M4Gy)
Tab positions are 'pre-set' so if a column is not wide enough to accommodate a particular entry then a tab position is missed and the next one is used.

Change 'Years' to 'Year' and you'll see the difference.

You are better off using <iomanip> and setw() functionality.
Yes got it. But can you please explain in detail (or give a link) why such a thing happens. Also I want equal spacing. But if i give the following command, I got less space between "Rate of" and "Initial Amount" as compared to others. What should I do ?

cout<<"Rate of"<<setw(18)<<"Initial Amount"<<setw(18)<<"5 Years"<<setw(18)<<"10 Years"<<setw(18)<<"15 Years"<<"\n";
Last edited on
Control of how text (including tab characters) is displayed is the job of your terminal, not of C++'s streams.

The manipulator std::setw(n) sets the field width of the following token to n fill characters - in particular, it is not a blank space n fill characters in size.

See
http://en.cppreference.com/w/cpp/io/manip/setw
Understood.
Thisgives correctly.
cout<<"Rate of"<<setw(19)<<"Initial Amount"<<setw(10)<<"5 Years"<<setw(10)<<"10 Years"<<setw(10)<<"15 Years"<<"\n";
If you simply want equal spacing between fields, just do something like this:

1
2
std::string const spacer{10, ' '}; // a spacer is 10 space characters:
std::cout << "Rate of" << spacer << "Initial amount" << spacer <<  ... etc ...;


setw is useful for printing text that should be aligned in columns.
Last edited on
closed account (48T7M4Gy)
It's like tabs on typewriters and word processors. They are set positions across the page, generally columns are 10 spaces wide.

https://stackoverflow.com/questions/13094690/how-many-spaces-for-tab-character-t

BTW: The tab character '\t' (not "\t")

Also, if your cout statement is the heading to the table of interest payments then you are making life very difficult for yourself.
1
2
cout<<"Rate of Initial   Amount 5 Years   10 Years   15 Years\n";
cout << setw(5) << r1 << setw(10) << amount5 << setw(10) << ... <<'\n';


Adjust those two lines by adding spaces manually to the first and adjusting the setw amounts to suit what you want.
I used setw to add spaces manually and got the desired output as shown in my previous reply. Thanks to all for your help
Topic archived. No new replies allowed.