C++ 标准库中是否有等效于 std::endl 的选项卡?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22057010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a tab equivalent of std::endl within the standard library?
提问by matthewrdev
Using C++, is there an equivalent standard library constant for '\t'
like there is for a newline?
使用 C++,是否有一个等效的标准库常量,'\t'
就像换行符一样?
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).
(我知道我可以插入一个,'\t'
但我想满足我的好奇心)。
回答by Brian
No. std::endl
isn't a newline constant. It's a manipulatorwhich, in additionto inserting a newline, also flushesthe stream.
号std::endl
是不是换行不变。它是一个操纵器,除了插入换行符外,还刷新流。
If you justwant 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.
如果你只想添加一个换行符,你应该只插入一个'\n'
. 如果您只想添加一个选项卡,只需插入一个'\t'
. 没有std::tab
或任何东西,因为插入选项卡并刷新流并不是一个常见的操作。
回答by Trevor Hickey
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.
我不建议这样做,但我想添加一个完整的解决方案。
回答by Pranit Kothari
Actually, it is not needed.
实际上,它是不需要的。
Because endl
first does the same job of inserting a newline as \n
, and then also flushes the buffer.
因为endl
首先执行与 插入换行符的相同工作\n
,然后还刷新缓冲区。
Inserting \t
on a stream does not require to flush it after .
\t
在流上插入不需要在 .
回答by Sly_TheKing
No.
不。
There are only std::ends
(insert null character) and std::flush
(flush the stream) output manipulators besides std::endl
in ostream include file.
除了ostream 包含文件之外,只有std::ends
(插入空字符)和std::flush
(刷新流)输出操纵器std::endl
。
You can find others in ios and iomanip include files. Full list is here
您可以在 ios 和 iomanip 包含文件中找到其他人。完整列表在这里