c++ - 是否可以按顺序执行“cout”?
问题描述
是否可以获得如图所示但具有特定顺序(从下到上)的原始输出?
cout<<R"(programming )";sleep(10); cout<<R"(
newbie at )";sleep(5); cout<<R"(
i'm )"; sleep(1);
output: programming------>printed third at the first line
newbie at------->printed second at the second line
i'm--------->printed first at the third line
注意:我不是说反转输出。
编辑:我猜简单的技巧是将它们的颜色设置为黑色,这将使它们“消失”,然后通过使用嵌套的 for 循环,我可以通过线条移动并延迟将它们的颜色一一更改为白色,但我不知道如何实际操作
解决方案
#include <chrono>
#include <future>
#include <iostream>
#include <thread>
int main()
{
using namespace std::chrono_literals;
auto print_first_line = std::async(std::launch::async, []() {
std::this_thread::sleep_for(6s);
std::cout << "programming\n" << std::flush;
});
auto print_second_line = std::async(std::launch::async, []() {
std::this_thread::sleep_for(3s);
std::cout << "newbie at\n" << std::flush;
});
auto print_third_line = std::async(std::launch::async, []() {
std::this_thread::sleep_for(1s);
std::cout << "i'm\n" << std::flush;
});
print_first_line.wait();
print_second_line.wait();
print_third_line.wait();
return 0;
}
如评论中所述,无法以std::cout
这种方式进行控制。但是可以使用线程来为您控制时间。这是一个使用std::async
from<future>
多线程打印语句的快速而肮脏的示例。
第一个参数std::async
明确告诉它异步启动,因为它可以在不创建新线程的情况下启动。第二个参数是一个带有睡眠定时器和打印语句的 lambda。
值得注意的是,您可能需要一个额外的编译器参数。我目前的测试是在 WSL (Debian) 中,所以我使用的编译命令是启用多线程的参数clang++ -Wall -Wextra -pthread main.cpp
在哪里。-pthread
对于您的平台,可能会有所不同。
正如所建议的那样,这种情况可能会更好地使用更通用的功能;类似的东西delay_print()
。这是一个可能的实现。
#include <array>
#include <chrono>
#include <cstdint>
#include <future>
#include <iostream>
#include <string>
#include <thread>
void delay_print(const std::chrono::duration<std::int64_t> &time,
std::string message)
{
std::this_thread::sleep_for(time);
std::cout << message << std::flush;
}
int main()
{
using namespace std::chrono_literals;
std::array<int, 4> seconds{7, 4, 2, 1};
std::array<std::string, 4> phrases{"How\n", "Now\n", "Brown\n", "Cow\n"};
auto print_line_01 =
std::async(std::launch::async, &delay_print,
std::chrono::seconds(seconds[0]), phrases[0]);
auto print_line_02 =
std::async(std::launch::async, &delay_print,
std::chrono::seconds(seconds[1]), phrases[1]);
auto print_line_03 =
std::async(std::launch::async, &delay_print,
std::chrono::seconds(seconds[2]), phrases[2]);
auto print_line_04 =
std::async(std::launch::async, &delay_print,
std::chrono::seconds(seconds[3]), phrases[3]);
print_line_01.wait();
print_line_02.wait();
print_line_03.wait();
print_line_04.wait();
return 0;
}
推荐阅读
- node.js - 将文件从 Angular 发送到 Nodejs - 无法读取未定义的属性“标题”
- java - iot-service-client azure-iot-sdk java 的企业代理
- javascript - React 组件中状态的更新时间问题(需要单击 2 次而不是 1 次)
- reactjs - gatsby remark 图片不显示图片
- r - 根据 2 列中的值重新排序 ggplot 中的标签
- c# - c# 从继承的类对象构造一个类
- pyspark - Pyspark - 更新 udf 中的列表
- jquery - 如何从另一个动态创建的按钮触发动态创建的按钮
- reactjs - 如何在 React 中解决这个加载程序问题?
- php - 想在 name.php 中使用 index.php 的输入