Search code examples
switch-statementdevaluate

Switch statement always resolves to default instead of case


So I've recently been trying out D, as many programmers I know are recommending I learn it over C++.

I'm using the DMD Compiler v2.057, and this is my code:

while(cliLoopC)
{
    write("?> ");
    string iPt_ = std.string.tolower(readln());
    switch (iPt_)
    {
        default: writeln(E_URECCOM); break;
        case "test":
            writeln("Hello!");
            break;
    }
}

The program is that, whenever I type in test, so it should go to the case instead of the default, it just prints the contents of E_URECCOM (which is a constant char[] that contains UNRECOGNISED COMMAND\n).

I don't see what's happening to make it do this. Any ideas?


Solution

  • Edit: Adam D. Ruppe's answer is the correct answer in saying:

    Yes, there's a \n at the end of readln. Try using std.string.strip(readln());

    I just wanted to throw that in there since my answer still has the check

    My answer: The default case is the catch all case, so it looks best (and is conventional) at the end

    like this

    while(cliLoopC)
    {
        write("?> ");
        string iPt_ = std.string.tolower(readln());
        switch (iPt_)
        {
            case "test":
                writeln("Hello!");
                break;
            default: writeln(E_URECCOM); break;
        }
    }