在单独的线程

时间:2017-11-09 13:47:31

标签: c++ multithreading c++11 io

我正在程序中运行两个线程。一个线程每隔一秒发送一次经过秒,而另一个线程运行一个while循环,该循环使用getline和cin从一个shell或命令行中获取用户的输入。

我的问题是,当用户输入某些内容时,只要用户输入的内容最终会发送到cout,最终会看起来像this一样凌乱。

有什么方法可以移动用户在向cout发送内容时输入一行的内容吗?或者也许是一些替代的io呢?

我希望输出看起来更像this

这是一些额外的细节和一些代码:

#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 Passed\n";
    }
}

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 sorry\n";
        }

    }         //END OF USER INPUT LOOP

    t.join(); //WAITING FOR OTHER THREAD TO FINISH
    return 0;
}

0 个答案:

没有答案