You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ncurses实现同一行连续输入输出的简化方案问询

关于ncurses同一行连续输入输出的简洁实现方案

当前繁琐的同一行输入输出实现

nocbreak();
echo();
mvwprintw(game->prompt, 1, 0, "Move from? ");
wgetnstr(game->prompt, input, 4);
wgetch(game->prompt);

/* find first not empty character and set cursor on it */
wmove(game->prompt, 1, getmaxx(game->prompt) - 1);
while ((winch(game->prompt) & A_CHARTEXT) == ' ')
    wmove(game->prompt, 1, getcurx(game->prompt) - 1);
wmove(game->prompt, 1, getcurx(game->prompt) + 2);

wprintw(game->prompt, "To? ");
wgetnstr(game->prompt, input, 4);

需求说明

该方案过于繁琐,希望找到更简便的方式丢弃换行符,实现同一行连续输入输出——直接连续调用IO函数就能达成Move from? <input1> To? <input2>的效果,无需上述规避换行的取巧手段。

尝试过用getch处理换行、切换nonl()/nl()模式,但均未对用户输入的换行行为产生预期影响。

默认行为与期望行为对比

默认代码

getstr(input)
printw("Hello")

默认行为

my input here
Hello

期望行为

my input hereHello

现有自定义解决方案(基于@n.m.couldbeanAI建议)

int
wread(WINDOW *win, char *input, int maxlen)
{
    int ch;
    char *beg = input;
    doupdate();
    curs_set(1);
    noecho();
    cbreak();
    keypad(win, TRUE);
    while ((ch = wgetch(win)) != '\n') {
        switch (ch) {
        case KEY_BACKSPACE:
            if (input - beg <= 0) continue;
            wmove(win, getcury(win), getcurx(win) - 1);
            wdelch(win);
            input--;
            break;
        default:
            if (input - beg >= maxlen) continue;
            waddch(win, ch);
            *(input++) = ch;
            break;
        }
    }
    curs_set(0);
    return input - beg;
}

疑问

想确认是否存在更简洁的实现方式。


内容的提问来源于stack exchange,提问作者yan3ku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 07:43:17