首页 > 解决方案 > 是否可以按顺序执行“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 循环,我可以通过线条移动并延迟将它们的颜色一一更改为白色,但我不知道如何实际操作

标签: c++c++11c++14c++17

解决方案


#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::asyncfrom<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;
}

推荐阅读