用 C 语言制作一个 REPL,看起来不错

Oz1*_*123 2 c loops tui read-eval-print-loop

我正在编写带有类似 Shell 界面的小程序。我的ui是:

void cli_ui(void){
    bool loop = true ;
    char response[CHARSIZE];
    while (loop) {
    puts("cofre>");
    fgets(response, CHARSIZE, stdin);
    ....
    }

}
Run Code Online (Sandbox Code Playgroud)

我的问题是在提示后读取输入:

cofre>
# input is expected here
Run Code Online (Sandbox Code Playgroud)

我想要的是:

cofre> #input is expected here
Run Code Online (Sandbox Code Playgroud)

你会怎么做?

dav*_*pfx 6

问题在于,puts() 写入字符串并用换行符替换尾随的空值,这会产生一个新行。

答案是使用fputs()。有点令人惊讶的是,fputs() 的作用与 puts() 不同,而是输出不带尾随换行符的字符串。所以。

fputs("cofre>", stdout);
Run Code Online (Sandbox Code Playgroud)

有些人会建议您使用 printf(),但这将是一个错误。当您使用 fgets() 时,您应该将其与 fputs() 配对。好处是您可以显式地使用标准输入和输出,因此您将能够从脚本驱动 REPL。

请注意,在某些实现中, fgets() 和 fputs() 可能会被缓冲,但这不是您想要的。在某些情况下,您可能需要使用低级 I/O,例如 cpus/cgets()。这些都是非标准的。