I’m writing a console based application that prompts a user for a series of questions. E.g:
“Enter a record to open:”
“Do you want to do X?”
“Do you want to do Y?”
“Are you sure you want to continue?”
If the user enters nothing at any prompt I want to go up one level. This is easy using goto. The only other way I can think of to do it is nested for loops which looks far uglier and gets pretty unwieldy for more than a couple of prompts. There must be an easy way to do this though, I just can’t think of it.
You’re basically writing a very simple state machine – use functions to represent every state: (I’ll use random pseudocode, since you didn’t specify a language)
this is a trivial approach. In some languages the call stack will grow, in others it won’t. If you have a language which causes the stack to grow, you can use trampolines to prevent it, by rewriting
get_informationto do:Or even abstracting the question and memory address of result in some
questionstructure:and then running in a loop, calling
question* run_question(question*), going to ->next, or ->prev depending on the answer, until the result is NULL (as a stop condition, when results are filled in and no questions are left).The last solution is probably the most “normal one” if you use an imperative language with direct pointer access.