简体   繁体   English

当用户这样说时停止 while / for 循环

[英]stopping a while / for loop when an user says so

i'm new to c++ so I only kind of know iostream and the syntax of the language.我是 c++ 的新手,所以我只知道 iostream 和语言的语法。

I am writing a program that creates an infinite amount of.txt files using fstream but i'm kind of stuck, I want it to have a menu in the program so the user could interfere with the process with the help of commands I will code in void functions("pause", "stop", etc...)我正在编写一个程序,该程序使用 fstream 创建无限数量的 .txt 文件,但我有点卡住了,我希望它在程序中有一个菜单,以便用户可以在我将编码的命令的帮助下干扰该过程在无效函数中(“暂停”、“停止”等...)

It means that the process of creating.txt files should run constantly but that the user could also write in a cin>> the keywords shown above to interfere with the process这意味着创建 .txt 文件的过程应该不断运行,但用户也可以在 cin>> 中写入上面显示的关键字以干扰该过程

I plan to write multiple commands so I'll surely use switch statement in the future but to show you my problem I'll only use a while loop with one command So I've tried things like that:我计划编写多个命令,所以将来肯定会使用 switch 语句,但为了向您展示我的问题,我只会在一个命令中使用 while 循环所以我尝试过这样的事情:

void stop()
{
return 0;
}

int main()
{
string command= "";
int i=1;

if (command!="stop")
{
     while (i<=2)
     {
     CreateNewFile();
     cin >> command;
     }

} else

{
stop();
}
}

But the problem with this kind of loop is that it asks the user to write something everytime in order to reset the loop and it is this thing in particular that I want to avoid... I want to keep the loop running as long as my user wants it to但是这种循环的问题在于它要求用户每次都写一些东西来重置循环,而我特别想避免这种事情......我想保持循环运行只要我的用户希望它

I'm sure that the answer is really simple but i've not found any help by asking google so i'll tr to ask you guys.我确信答案非常简单,但我没有通过询问谷歌找到任何帮助,所以我会问你们。

Thank you in advance to those who will take the time to asnwer me提前感谢那些愿意花时间回答我的人

So after a while this is basically the simplest solution:所以过了一会儿,这基本上是最简单的解决方案:

#include <iostream>
#include <thread>
#include <string>
static bool finished = false;
void createFile() {
    while (!finished) {
        //Your code
    }
}

int main() {
    std::string answer;
    std::thread question(createFile);
    std::cin >> answer;
    if (answer == "stop") {
        finished = true;
    }
    question.join();
    return 0;
}

Here we create a thread which will keep running until they type stop.在这里,我们创建一个线程,它将一直运行直到他们键入 stop。 I ran the code and it was working I made it print out 1 until I wrote stop.我运行了代码并且它正在工作我让它打印出 1 直到我写停止。

My advise, Adam, is to change your problem description so you ask user how many files they want to create, and then run the loop that many times:我的建议,亚当,是改变你的问题描述,所以你问用户他们想要创建多少个文件,然后多次运行循环:

for(;;) {
  unsigned n;
  cout << "How many files do you want to create (0 to stop)? ";
  cin >> n;
  if(!n) break;
  for(unsigned i = 0; i < n; i++) {
    CreateNewFile();
  }
}

I had something on this line wherein the thread that's doing the actual work continues and only processes commands if the user wants to.我在这条线上有一些东西,其中正在执行实际工作的线程继续进行,并且仅在用户愿意时才处理命令。

#include <iostream>
#include <string>
#include <thread>
#include <stack>
#include <chrono>
#include <mutex>

int main() {
    std::stack<std::string> commandQueue;
    std::mutex m;
    int i = 0;
    std::thread worker([&]() {
        bool suspend = false;
        while(true) {
            {
                const std::lock_guard<std::mutex> lock(m);
                if(!commandQueue.empty()){
                    std::string command = commandQueue.top();
                    commandQueue.pop();
                    if(command == "continue"){
                        suspend = false;
                        //process continue
                    } else if (command == "pause"){
                        suspend = true;
                        //process other commands....
                    } else if(command == "stop") {
                        //process stop
                        return; //exit thread
                    } 
                }
            }
            //Commands processed, continue as usual
            if(!suspend) {//Process only if not paused
                using namespace std::chrono_literals;
                //Continue creating files or whatever it is that needs to be done continuously
                std::this_thread::sleep_for(500ms);
                i++;
                //std::cout<<"Value of i is "<<i<<'\n';
                //CreatFileName();
            }
        }
    });
    std::string command;
    do {
        std::cout<<"Enter commands to interact\n";
        std::cin>>command;
        {
            const std::lock_guard<std::mutex> lock(m);
            commandQueue.push(command);
        }
    }while(command != "stop");
    worker.join();
    std::cout<<"After execution, value of i is "<<i<<'\n';
}

Of course, the output of this specific example is a bit ugly because it is printing to the console from 2 different threads but the commands like stop , pause , continue are processed fine since there's only one thread (the main thread) that reads in the commands but since this is just to demonstrate how one can possibly achieve what you intend to, I didn't spend up too much time on the output aesthetics.当然,这个特定示例的 output 有点难看,因为它从 2 个不同的线程打印到控制台,但是像stoppausecontinue这样的命令处理得很好,因为只有一个线程( main线程)读取命令,但由于这只是为了演示如何实现您的意图,因此我没有在output美学上花费太多时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM