在C ++中使用ncurses读取字符串 [英] Read a string with ncurses in C++

查看:139
本文介绍了在C ++中使用ncurses读取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C ++编写基于文本的游戏.在某个时候,我要求用户输入与正在玩的不同玩家相对应的用户名.

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.

我目前正在从ncurses读取单个字符,如下所示:

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();

我已经看到了许多使用ncurses的指南,它们都使用一组其他函数没有的不同函数.据我所知,不赞成和不赞成使用的功能之间的界线不是很清楚.

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.

推荐答案

如何?

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;
}

我不建议使用替代的*scanw()函数系列.您可能要使用临时的char []缓冲区,具有所有问题的基础*scanf()功能,以及*scanw()的规范说明它返回ERROK而不是扫描的项目数,从而进一步减少了有用.

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.

虽然getstr()(由用户indiv建议)看起来比*scanw()更好,并且对功能键进行了特殊处理,但仍然需要一个临时的char [],如果没有任何帮助,我会尽量避免使用C ++代码中的那些功能否则,请避免使用一些任意的缓冲区大小.

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.

这篇关于在C ++中使用ncurses读取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆