我在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;
发布于 2020-03-06 18:43:56
流操纵器只是一个函数,流通过其中一个operator <<
重载(链接中的10-12)调用它自己。你只需要声明一个这样的函数(或者可以转换成合适的函数指针):
constexpr auto m = [](std::ostream &s) -> std::ostream& {
return s << std::setw(5) << std::scientific << std::left;
};
std::cout << m << 12.3 << '\n';
发布于 2020-03-06 18:41:45
您可以编写自己的操纵器:
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-操纵器修改流的状态。因此,它不能完全按照您要求的方式工作。您正在修改m
的状态。将状态从一个流转移到另一个流是可能的,但比必要的复杂。
注意:注意我定义自定义io-manipulator的方式是可以的,但是要查看更符合流操纵器精神的实现,请参阅this answer (通常io-manipulator是函数,我使用了一个标签,它需要更多一点的样板)。
https://stackoverflow.com/questions/60562269
复制相似问题