Search code examples
ddo-while

do-while doesn't quit on first 'q'


So I'm working on a simple little text-based game in D to gain some experience working with the language. Here is a do-while loop that I'm currently struggling with:

do{
  writeln("a. Advance 1 year\tc. Advance 10 years\tq. Quit");
  writeln("b. Advance 5 years\td. Modify faction");

  input = chomp(stdin.readln());

  switch(input){
    ...
    default:
      break;
  }
  writeln(input[0]);
}while(input[0] != 'q');

Now the problem I'm running into is that when I hit q and enter the loop doesn't exit. It just keeps going. But then after the first time q is input, another q will terminate the loop. The writeln is in there as a sanity check, and it prints out the characters I type in exactly as typed. I feel like I'm going crazy, but it's probably just a simple type-o or something you guys will spot instantly. Nothing in the switch statement modifies 'input'.

EDIT: Okay some people have been asking to see all of the code. Here it is: http://pastebin.com/A7qM5nGW

When I said nothing in the switch modified input, it was to hide the fact I hadn't written anything in the switch yet. I've been trying to get the quit part to work right before adding the more complicated stuff. Also, here's a sample file for what I run it on: http://pastebin.com/4c2f4Z5N


Solution

  • Okay my friend found it. It has nothing to do with the while loop itself. I briefly forgot that args[0] is the name of the program. So it's actually running through the parent loop once with nothing, then actually quitting, and then running through the appropriate loop. It was fixed by making the parent loop like so...

    foreach(filename; args[1..$]){
        ...
        do{
            ...
        while(input[0] != 'q');
    }
    

    as opposed to:

    foreach(filename; args){
    

    etc...