是否有一种简单的方法可以将输出缩进到ofstream对象?我有一个C ++字符数组,它是null终止并包含换行符。我想将它输出到流中,但是用两个空格缩进每一行。有没有一种简单的方法可以使用流操纵器来执行此操作,例如您可以使用特殊指令更改整数输出的基数,还是必须手动处理数组并在检测到的每个换行符时手动插入额外的空格?
似乎字符串:: right()操纵器已关闭:
http://www.cplusplus.com/reference/iostream/manipulators/right/
感谢。
- 威廉
答案 0 :(得分:21)
这是使用方面的完美情况。
codecvt facet的自定义版本可以融入流中。
所以你的用法如下:
int main()
{
/* Imbue std::cout before it is used */
std::ios::sync_with_stdio(false);
std::cout.imbue(std::locale(std::locale::classic(), new IndentFacet()));
std::cout << "Line 1\nLine 2\nLine 3\n";
/* You must imbue a file stream before it is opened. */
std::ofstream data;
data.imbue(indentLocale);
data.open("PLOP");
data << "Loki\nUses Locale\nTo do something silly\n";
}
方面的定义稍微复杂一点 但重点是使用facet的人不需要知道格式化的任何信息。格式化的应用与流的使用方式无关。
#include <locale>
#include <algorithm>
#include <iostream>
#include <fstream>
class IndentFacet: public std::codecvt<char,char,std::mbstate_t>
{
public:
explicit IndentFacet(size_t ref = 0): std::codecvt<char,char,std::mbstate_t>(ref) {}
typedef std::codecvt_base::result result;
typedef std::codecvt<char,char,std::mbstate_t> parent;
typedef parent::intern_type intern_type;
typedef parent::extern_type extern_type;
typedef parent::state_type state_type;
int& state(state_type& s) const {return *reinterpret_cast<int*>(&s);}
protected:
virtual result do_out(state_type& tabNeeded,
const intern_type* rStart, const intern_type* rEnd, const intern_type*& rNewStart,
extern_type* wStart, extern_type* wEnd, extern_type*& wNewStart) const
{
result res = std::codecvt_base::noconv;
for(;(rStart < rEnd) && (wStart < wEnd);++rStart,++wStart)
{
// 0 indicates that the last character seen was a newline.
// thus we will print a tab before it. Ignore it the next
// character is also a newline
if ((state(tabNeeded) == 0) && (*rStart != '\n'))
{
res = std::codecvt_base::ok;
state(tabNeeded) = 1;
*wStart = '\t';
++wStart;
if (wStart == wEnd)
{
res = std::codecvt_base::partial;
break;
}
}
// Copy the next character.
*wStart = *rStart;
// If the character copied was a '\n' mark that state
if (*rStart == '\n')
{
state(tabNeeded) = 0;
}
}
if (rStart != rEnd)
{
res = std::codecvt_base::partial;
}
rNewStart = rStart;
wNewStart = wStart;
return res;
}
// Override so the do_out() virtual function is called.
virtual bool do_always_noconv() const throw()
{
return false; // Sometime we add extra tabs
}
};
答案 1 :(得分:2)
嗯,这不是我正在寻找的答案,但如果没有这样的答案,这里有一种方法可以手动完成:
void
indentedOutput(ostream &outStream, const char *message, bool &newline)
{
while (char cur = *message) {
if (newline) {
outStream << " ";
newline = false;
}
outStream << cur;
if (cur == '\n') {
newline = true;
}
++message;
}
}
答案 2 :(得分:2)
如果是你的情况,overflow()成员只会测试'\ n',然后在需要之后添加缩进(正是你在indentedOuput
函数中所做的,除了{{1}将成为streambuf的成员)。您可能有一个设置来增加或减少缩进大小(可能通过操纵器访问,操纵器必须执行dynamic_cast以确保与流关联的streambuf具有正确的类型;有一种添加用户的机制数据流 - basic_ios :: xalloc,iword和pword - 但是我们想在streambuf上行动。
答案 3 :(得分:2)
我在Martin的基于 codecvt facet 的建议上取得了很好的成功,但我在OSX上的std :: cout上使用它时遇到了问题,因为默认情况下这个流使用基于basic_streambuf的streambuf忽略了充满希望的方面。以下行切换std :: cout和friends使用基于basic_filebuf的streambuf,它将使用imbued facet。
std::ios::sync_with_stdio(false);
由于相关的副作用,iostream标准流对象可以独立于标准C流运行。
另一个注意事项是,因为这个facet没有静态的std :: locale :: id,这意味着调用std :: has_facet&lt; IndentFacet&gt;在语言环境中始终返回true。添加std :: local :: id意味着未使用facet,因为basic_filebuf会查找基类模板。
答案 4 :(得分:2)
我已将Loki Astarti的解决方案推广到任意缩进级别。该解决方案具有一个漂亮,易于使用的界面,但实际的实现有点可疑。它可以在github上找到:https://github.com/spacemoose/ostream_indenter
github repo中有一个更复杂的演示,但是给出了:
#include "indent_facet.hpp"
/// This probably has to be called once for every program:
// http://stackoverflow.com/questions/26387054/how-can-i-use-stdimbue-to-set-the-locale-for-stdwcout
std::ios_base::sync_with_stdio(false);
// This is the demo code:
std::cout << "I want to push indentation levels:\n" << indent_manip::push
<< "To arbitrary depths\n" << indent_manip::push
<< "and pop them\n" << indent_manip::pop
<< "back down\n" << indent_manip::pop
<< "like this.\n" << indent_manip::pop;
}
它产生以下输出:
I want to push indentation levels:
To arbitrary depths
and pop them
back down
like this.
我很感激有关代码效用的任何反馈。
答案 5 :(得分:1)
没有简单的方法,但已经有很多关于复杂的文章 实现这一目标的方法。 Read this article有一个很好的解释 话题。不幸的是,Here is another article是德语。但 its source code可以帮助你。
例如,您可以编写一个记录递归结构的函数。对于每个递归级别,缩进都会增加:
std::ostream& operator<<(std::ostream& stream, Parameter* rp)
{
stream << "Parameter: " << std::endl;
// Get current indent
int w = format::get_indent(stream);
stream << "Name: " << rp->getName();
// ... log other attributes as well
if ( rp->hasParameters() )
{
stream << "subparameter (" << rp->getNumParameters() << "):\n";
// Change indent for sub-levels in the hierarchy
stream << format::indent(w+4);
// write sub parameters
stream << rp->getParameters();
}
// Now reset indent
stream << format::indent(w);
return stream;
}
答案 6 :(得分:0)
简单的空白操纵器
struct Whitespace
{
Whitespace(int n)
: n(n)
{
}
int n;
};
std::ostream& operator<<(std::ostream& stream, const Whitespace &ws)
{
for(int i = 0; i < ws.n; i++)
{
stream << " ";
}
return stream;
}