65

Using C++, is there an equivalent standard library constant for '\t' like there is for a newline?

Ideally:

std::stringstream ss;
ss << std::tab << "text";

If not, why is this the case?

(I'm aware I can just insert a '\t' but I'd like to sate my curiosity).

matthewrdev
  • 11,930
  • 5
  • 52
  • 64

4 Answers4

108

No. std::endl isn't a newline constant. It's a manipulator which, in addition to inserting a newline, also flushes the stream.

If you just want to add a newline, you're supposed to just insert a '\n'. And if you just want to add a tab, you just insert a '\t'. There's no std::tab or anything because inserting a tab plus flushing the stream is not exactly a common operation.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • 4
    @Ksletmo, the sequence inserted by `endl` is always `'\n'`; it has nothing to do with the platform's preferred text-file line ending. – Rob Kennedy Feb 27 '14 at 01:26
  • 3
    To put that another way: the newline character `'\n'` is a standard ASCII character just like `'\t'` is. The effect of writing the single character `'\n'` to a file opened in text mode varies by platform. As Rob says, that's nothing to do with `std::endl`, which just writes a character and does a flush. It doesn't know or care what the stream does with that character. – Steve Jessop Feb 27 '14 at 01:58
  • How is `foo << '\t'` different that `foo << 10` ('\t' is encoded as a 10 in ascii). I want a tab, not a formatted 10. – wcochran Jun 30 '20 at 19:13
25

If you want to add the feature yourself, it would look like this:

#include <iostream>

namespace std {
  template <typename _CharT, typename _Traits>
  inline basic_ostream<_CharT, _Traits> &
  tab(basic_ostream<_CharT, _Traits> &__os) {
    return __os.put(__os.widen('\t'));
  }
}

int main() {

  std::cout << "hello" << std::endl;
  std::cout << std::tab << "world" << std::endl;
}

I don't recommend doing this, but I wanted to add a solution for completeness.

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
4

No.

There are only std::ends (insert null character) and std::flush (flush the stream) output manipulators besides std::endl in ostream include file.

You can find others in ios and iomanip include files. Full list is here

Sly_TheKing
  • 518
  • 7
  • 14
4

Actually, it is not needed.

Because endl first does the same job of inserting a newline as \n, and then also flushes the buffer.

Inserting \t on a stream does not require to flush it after .

sergiol
  • 4,122
  • 4
  • 47
  • 81
Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137