Question

I'm trying the function below to get a filename while allowing for 'ESC' press to go back

but for some reason _getch() always returns [1 '\x1'] and what is being printed is a smiley face, even for BackSpace (which is nice and all, but absolutely not what I want to happen).

  • What's going on here?

Other insights on how to improve the code are more than welcome! (I've recently finished my first year in college so I'm still pretty new to programming)

string& Get_Filename()
{
    char ch;
    string name;

    while (ch = _getch() != 'CR')
    {
        if (ch == 'ESC')
            throw RESTART;
        if (ch == 'BS')
        {
            name.pop_back();
            cout << 'BS';   // Also, will this correctly delete or will I need to
        }                   // << '\b' << ' ' << '\b'?
        else
        {
            name += ch;
            cout << ch;
        }
    }
    return name;
}
Was it helpful?

Solution

Read about operator precedence here: http://en.cppreference.com/w/cpp/language/operator_precedence

One of the problems is in the line

while (ch = _getch() != 'CR')

since != has a higher precedence than the assignment operator

what you're actually asking is:

while( ch = (_getch() != 'CR') )

and thus getting the result of the expression instead of the character you wanted (which is the integral conversion bool->char defined in the standard §4.7/4 as 0 or 1)

Furthermore: you're returning a reference to a local variable. Make sure to return a by-value copy or something which doesn't fall out-of-scope.

Finally: _getch() returns the character read from the console, you can't "intercept" special key chords (e.g. Ctrl-D or Esc). Read more here: http://msdn.microsoft.com/it-it/library/078sfkak.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top