is setw() and "\t" the same thing? [closed]
Sophia Terry
Is setw() and "\t" the same thing tho?
And are they similar to "space" too?.
Can I use setw() in the place of "\t" or would it result in a completely different output?
2 Answers
They have almost nothing in common.
std::setw(int n) set the width of the next element that goes into the stream. So if you have things like:
std::cout << "Hi," << std::setw(12) << "there!";This would print:
Hi, there! ^^^^^^ <- 6 empty spaces were made here to fill the widthIf you set the width to be longer than the actually object streamed in to it, it will automatically fill them with spaces.
On the other hand, '\t' is a predefined escape sequence. And it will behave similar to when you type a tab in many text editors. Also note that it is actually a character, you could put that in any strings:
std::cout << "\tHi,\tthere!";This would print:
Hi, there!
^^^^ ^ <-- both of them are tabsNote those tabs were made different sizes, you should be able to observe similar behaviors when using tabs in text documents. It will try to fill the current 4 block text with spaces if it was not filled yet.
No they are not same at all.
"\t" : allocates 4 spaces;
setw() : setWidth() is a function defined in iomanip header file.
It takes a integer as parameter and allocates the width of value of the integer.
Take for an example : setw(7) It will allocate 7 spaces to you
cout<<setw(7)<<"Hi"<<"**";Output will be : Hi + 5 Spaces + **
5 Spaces because in total you requested 7 spaces and 2 are occupied by 2 character of word "Hi".
This function is highly used where you want to display something in a very proper format.
2