Read a string with ncurses in C++

不打扰是莪最后的温柔 提交于 2020-01-21 11:45:07

问题


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.



来源:https://stackoverflow.com/questions/26920261/read-a-string-with-ncurses-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!