简体   繁体   中英

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.

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...)

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

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:

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. I ran the code and it was working I made it print out 1 until I wrote stop.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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