C++同时输入输出到控制台窗口 [英] C++ Input and output to the console window at the same time

查看:104
本文介绍了C++同时输入输出到控制台窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个服务器(主要用于 Windows,但如果我可以保持多平台状态会很酷)并且我只使用一个普通的控制台窗口.但是,我希望服务器能够执行诸如 say text_to_say_here 或 kick playername 等命令.我怎样才能有异步输入/输出?我已经用普通的 printf() 和 gets_s 尝试了一些东西,但这导致了一些非常......奇怪的东西.

I'm writing a server(mainly for windows, but it would be cool if i could keep it multiplatform) and i just use a normal console window for it. However, I want the server to be able to do commands like say text_to_say_here or kick playername, etc. How can i have a asynchronous input/output? I allready tried some stuff with the normal printf() and gets_s but that resulted in some really.... weird stuff.

我的意思是这样的1

谢谢.

推荐答案

利用 C++11 特性(即跨平台)的快速代码

Quick code to take advantage of C++11 features (i.e. cross-platform)

#include <atomic>
#include <thread>
#include <iostream>

void ReadCin(std::atomic<bool>& run)
{
    std::string buffer;

    while (run.load())
    {
        std::cin >> buffer;
        if (buffer == "Quit")
        {
            run.store(false);
        }
    }
}

int main()
{
    std::atomic<bool> run(true);
    std::thread cinThread(ReadCin, std::ref(run));

    while (run.load())
    {
        // main loop
    }

    run.store(false);
    cinThread.join();

    return 0;
}

这篇关于C++同时输入输出到控制台窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆