2

我在 ofstream 中链接了一些流操纵器,如下所示:

std::string filename = "output.txt";
std::ofstream outputFile;
outputFile.open(filename, std::ios::trunc);
outputFile << std::setw(5) << std::scientific << std::left << variable;

是否可以做这样的事情呢?:

std::string filename = "output.txt";
std::ofstream outputFile;
outputFile.open(filename, std::ios::trunc);
std::ostream m;
m << std::setw(5) << std::scientific << std::left;   // Combine manipulators into a single variable
outputFile << m << variable;
4

2 回答 2

4

A stream manipulator is just a function that a stream calls on itself through one of the operator << overloads (10-12 in the link). You just have to declare such a function (or something convertible to a suitable function pointer):

constexpr auto m = [](std::ostream &s) -> std::ostream& {
    return s << std::setw(5) << std::scientific << std::left;
};
std::cout << m << 12.3 << '\n';

See it live on Wandbox

于 2020-03-06T10:43:55.690 回答
3

您可以编写自己的操纵器:

struct my_manipulator{};

std::ostream& operator<<(std::ostream& o, const my_manipulator& mm) {
     o << std::setw(5) << std::scientific << std::left;
     return o;
};

这将允许你写

outputFile << my_manipulator{} << variable;

PS:Io-manipulators 修改流的状态。因此,它不能完全按照您要求的方式工作。您正在修改 的状态m。将状态从一个流转移到另一个流是可能的,但恕我直言,比必要的复杂。

PPS:请注意,我定义自定义 io-manipulator 的方式还可以,但是要查看更符合流操纵器精神的实现,请参阅此答案(通常 io-manipulators 是函数,我使用了一个需要一点点样板)。

于 2020-03-06T10:41:45.053 回答