how to "go back" in code

string command;
int main(){
cin >> command;
if (command == "exit"){
//code that exits the program
}
else{
cout << "Unknown command '"<<command<<"' try again";
cin >> command;
}
}

if the command entered is not exit the program asks for another command but when the next command is wrong the program closes how would i make it so that the programm keeps asking for valid comands?
You want to use a looping structure:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
std::string command;
while((std::cout << "Enter command: ") && std::getline(std::cin, command))
{
    if(command == "exit")
    {
        break;
    }
    else if(command == "blah")
    {
        std::cout << "Blah blah blah." << std::endl;
    }
    else
    {
        std::cout << "Unknown command." << std::endl;
    }
}
http://www.cplusplus.com/doc/tutorial/control/#loops
Last edited on
Thanks that helped alot.
What if i want the command to ask for parameters?
LB wrote:
You can easily split by spaces:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
std::string command;
while((std::cout << "Enter command: ") && std::getline(std::cin, command))
{
    std::vector<std::string> v; //will hold the command name and its arguments
    std::istringstream iss (command); //used for splitting by space
    while(iss >> command) //keep looping until we run out of arguments
    {
        v.push_back(command); //add each part of the command to the vector
    }
    if(v.size() < 1) //make sure the command wasn't empty
    {
        continue;
    }
    else if(v.front() == "exit")
    {
        break;
    }
    else if(v.front() == "blah" && v.size() == 2)
    {
        std::cout << "Blah blah blah: " << v[1] << std::endl;
    }
    else
    {
        std::cout << "Unknown command." << std::endl;
    }
}
Last edited on
Topic archived. No new replies allowed.