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).

4 Answers 4

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.

3
  • 4
    @Ksletmo, the sequence inserted by endl is always '\n'; it has nothing to do with the platform's preferred text-file line ending. Feb 27, 2014 at 1: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. Feb 27, 2014 at 1: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, 2020 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.

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 .

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.