Tuesday, July 28, 2009

C++ program. looping back after a command is given?

ok so this is my first C++ program and i was wondering how do i loop back to the original input after the help command is given.





cout %26lt;%26lt; "If you need help simply type help" %26lt;%26lt; endl;


cin %26gt;%26gt; r;


if (r == "help"){


cout %26lt;%26lt; "ALL commands except help must be typed in caps lock, now restart the program" %26lt;%26lt; endl;


system("PAUSE"); // how do i make this loop back to cin %26gt;%26gt; r??? without repeating the code


return EXIT_SUCCESS;


}





else if (r=="READY") {


[this is where the rest of the code will go]

C++ program. looping back after a command is given?
There are several ways to do this. Here is one to play with and maybe get some ideas.





int main()


{


cout %26lt;%26lt; "If you need help simply type help" %26lt;%26lt; endl;





while (true)


{


cin %26gt;%26gt; r;





if (r == "quit")


{


cout %26lt;%26lt; "bye";


break;


}





if (r == "help")


{





cout %26lt;%26lt; "ALL commands except help must be typed in caps lock, now restart the program" %26lt;%26lt; endl;


continue;


}





if (r=="READY")


{


do_whatever();


continue;


}


}





return(EXIT_SUCCESS);


}
Reply:Looks like you need a while loop. At the top, you put a "while(1)" i.e. "while something exists," basically looping your commands forever. Alternatively you can look up "for" loops... I don't know enough about those...
Reply:you can use a while loop or you can use a goto statement.





******* goto method ******


prompt:


cout %26lt;%26lt; "If you need help simply type help" %26lt;%26lt; endl;


cin %26gt;%26gt; r;


if (r == "help") {


cout %26lt;%26lt; "ALL commands except help must be typed in caps lock, now restart the program" %26lt;%26lt; endl;


system("PAUSE");


goto prompt;


}





else if (r=="READY") {


}





******* while method *********


while (r != "QUIT")


{


cout %26lt;%26lt; "If you need help, simply type help" %26lt;%26lt; endl;


do {


cin %26gt;%26gt; r;


if (r == "help")


cout %26lt;%26lt; "ALL commands except help must be typed in caps lock" %26lt;%26lt; endl;


system("PAUSE");


} while (r == "help");


if (r == "READY")


{


execute_code();


}


}


No comments:

Post a Comment