Read a string with ncurses in C++

2020-04-08 11:40发布

问题:

I'm writing a text-based game in C++. At some point, I ask the user to input user names corresponding to the different players playing.

I'm currently reading single char from ncurses like so:

move(y,x);
printw("Enter a char");
int char = getch();

However, I'm not sure how to a string. I'm looking for something like:

move(y,x);
printw("Enter a name: ");
std::string name = getstring();

I've seen many different guides for using ncurses all using a different set of functions that the other doesn't. As far as I can tell the lines between deprecated and non-deprecated functions is not very well defined.

回答1:

How about this?

std::string getstring()
{
    std::string input;

    // let the terminal do the line editing
    nocbreak();
    echo();

    // this reads from buffer after <ENTER>, not "raw" 
    // so any backspacing etc. has already been taken care of
    int ch = getch();

    while ( ch != '\n' )
    {
        input.push_back( ch );
        ch = getch();
    }

    // restore your cbreak / echo settings here

    return input;
}

I would discourage using the alternative *scanw() function family. You would be juggling a temporary char [] buffer, the underlying *scanf() functionality with all its problems, plus the specification of *scanw() states it returns ERR or OK instead of the number of items scanned, further reducing its usefulness.

While getstr() (suggested by user indiv) looks better than *scanw() and does special handling of function keys, it would still require a temporary char [], and I try to avoid those in C++ code, if for nothing else but avoiding some arbitrary buffer size.