C++ Input and output to the console window at the same time(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++同时输入输出到控制台窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++同时输入输出到控制台窗口


- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01