如何让输出流稍后执行某些操作
How do I make an output stream do something later?
我想让输出流稍后打印一些东西。我想让它像这样工作:
cout << printThisLater("Hello, World") << x << y << printItNow();
我希望流记住我传递给它的字符串。我该怎么做?
这是我尝试过的,但没有奏效:
#include <iostream>
#include <string>
std::string msg;
std::ostream& printThisLater(std::string str)
{
msg = str;
return // ??
}
std::string printItNow()
{
return msg;
}
int main()
{
int x = 10, y = 59;
std::cout << printThisLater("Hello World") << x << y << printItNow();
}
您只需将
以后要打印的数据附加到流中,并在需要时检索它。这是如何完成的:
#include <iostream>
#include <string>
class print_this_later {
std::string value;
public:
print_this_later(std::string const& value): value(value) {}
std::string const& str() const { return this->value; }
static int index() {
static int rc = std::ios_base::xalloc(); return rc;
}
static void erase(std::ios_base::event ev, std::ios_base& ios, int index) {
if (ev == std::ios_base::erase_event) {
delete static_cast<std::string*>(ios.pword(index));
}
}
};
std::ostream& operator<< (std::ostream& out, print_this_later const& value) {
void*& pword(out.pword(value.index()));
if (pword) {
std::unique_ptr<std::string> tmp(static_cast<std::string*>(pword));
pword = 0;
pword = new std::string(*tmp + value.str());
}
else {
out.register_callback(&print_this_later::erase, value.index());
pword = new std::string(value.str());
}
return out;
}
std::ostream& print_now(std::ostream& out) {
return out << *static_cast<std::string*>(out.pword(print_this_later::index()));
}
int main()
{
std::cout << print_this_later("world")
<< print_this_later("!")
<< "hello" << ", " << print_now << 'n';
}
基本思想是,print_this_later(string)
是一个对象,当string
"写入"到流时,它与流一起存储。该值存储在pword()
条目中:与
out.pword(index)
您可以访问与索引index
下的out
关联的void*&
。最初,该值将为 null,并将保留上次获取的值。由于只能存储一个void*
,因此对象被分配到堆上,需要清理。清理可以通过已注册的回调来完成,该回调在流被销毁时调用。
你为什么不直接使用std::cout
?默认情况下它是缓冲的,因此,在您在其上放置std::flush
或std::endl
或程序终止之前,它不会打印任何内容。
如果这对您不起作用,我会使用std::stringstream
来缓冲我的文本并写入
std::cout << ss.str() << std::flush;
当您需要实际输出时。
相关文章:
- 按下Arduino按钮后,如何在C#应用程序上执行操作
- 是否可以访问类数据成员并在析构函数中对它们执行操作?
- 如何让派生类在调用基类之前执行操作?
- CListCtrl 根据选定的行值执行操作
- 在服务器上执行操作的正确和 REST 方式?
- 是否可以拦截/检测关闭 PC 并首先执行操作的请求?
- 如何有效地使用 std::async 对指针数组执行操作
- 无法对套接字执行操作,因为系统缺少足够的缓冲区空间或队列已满
- 递归推动POP POSTFIX计算器无法正确执行操作,只需将最后一个数字作为结果
- QListWidgetItem 当按钮单击时执行操作
- 为什么C++没有简洁的语法允许在不定义计数器的情况下多次执行操作?
- 如何在标准库C/C++函数中进行gdb单步执行操作
- 如何对 n 个字符串执行操作,然后在C++中打印它们
- 从文件中读取运算符并执行操作C++
- 使用重载运算符在函数调用时执行操作
- 您如何选择在opencv-dnn上执行操作的设备
- 如何使用BoostSpirit.Qi增量解析(并对其执行操作)大文件
- 在remove_if删除元素之前,我可以滥用谓词对元素执行操作吗
- 在使用Qt修改任何复选框状态时执行操作
- 是否可以在不使用任何头文件的情况下在C++中执行I/O操作