用cout在单独的线程中输出用户输入上方的文本
我在一个程序中运行两个线程。 一个线程每秒发送一次到cout的时间,另一个线程运行一个while循环,该循环使用getline和cin以某种shell或命令行的形式从用户处获得输入。
我的问题是,无论用户输入什么内容,当用户输入内容时,只要有东西发送给cout,它最终会看起来像这样混乱。
有什么办法可以在用户输入cout时向用户输入一行内容? 或者也许有一些替代io这样做?
我宁愿输出看起来更像这样
以下是一些额外的细节和一些代码:
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <sstream>
#include <thread>
#include <chrono>
#include <vector>
using std::thread;
using std::vector;
using std::string;
using std::cout;
using std::cin;
void loop(bool &running)
{
int secondsElapsed = 0;
while (running)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
secondsElapsed++;
cout << std::to_string(secondsPassed) << " Seconds Passedn";
}
}
int main()
{
//STARTING OTHER THREAD RIGHT AWAY
bool running = true;
std::thread t(loop, std::ref(running));
string param;
string currentLine;
vector<string> params;
while (true)
{
//PARSING USER INPUT FOR EVALUATION
params.clear();
getline(cin, currentLine);
std::stringstream currentLineStream(currentLine);
//CHECKING SIZE OF USER INPUT TO SEE IF THERE IS ANY
if (currentLineStream.rdbuf()->in_avail() > 0)
{
while (getline(currentLineStream, param, ' '))
{
params.push_back(param);
}
//CAPITALISING FIRST PARAMETER TO MAKE EVALUATION EASIER
boost::to_upper(params[0]);
}
else
{
params.push_back("");
}
//FINISHED PARSING INPUT, EVALUATING
if (params[0] == "STOP")
{
running = false;
break;
}
else
{
cout << "Unknown Command, help menu not implemented yet sorryn";
}
} //END OF USER INPUT LOOP
t.join(); //WAITING FOR OTHER THREAD TO FINISH
return 0;
}
链接地址: http://www.djcxy.com/p/30819.html
上一篇: Outputting text above user input with cout in separate thread
下一篇: Using Threads(Use, Creation, etc) Making a thread run over the main