代码之家  ›  专栏  ›  技术社区  ›  Taylor Nichols

如果输入缓冲区不为空,则使用getchar()检测Ctrl+d

  •  0
  • Taylor Nichols  · 技术社区  · 6 年前

    我正在用 getchar() 对于缓冲输入。

    • 如果 Enter 按下时,解释器应处理缓冲区,然后提示输入新行。
    • 如果 Ctrl+d 按下,解释器应该处理缓冲区,然后退出。

    下面的代码运行,但不能完全满足第二个要求。

    #include <iostream>
    
    using namespace std;
    
    void shell() {
        for (int input;;) {
            // prompt at beginning of line
            std::cout << ">>> "; 
            while ((input = getchar()) != '\n') { 
                // still in current line
                if (input == EOF) {
                    // ctrl+d pressed at beginning of line
                    return;
                } 
                std::cout << "[" << (char)input << "]";
            }
            // reached end of line
        }
    }
    
    int main() {
        cout << "before shell" << endl;
        shell();
        cout << "shell has exited" << endl;
        return 0;
    }
    

    我的问题是 获取字符() 只返回 EOF 当缓冲区为空时。紧迫的 Ctrl+d键 中线原因 获取字符() 返回每个缓冲字符 除了 这个 EOF公司 性格本身。

    我如何确定 Ctrl+d键 是否按中线?

    我考虑过暂停一下。在这种方法中,解释器假设 Ctrl+d键 如果 获取字符() 在返回除换行外的其他内容后停止太长时间。这不是我最喜欢的方法,因为它需要线程,引入延迟,并且不清楚合适的等待时间。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Cheers and hth. - Alf    6 年前

    有一条正常的线 '\n' 最后。不是这样的 Ctrl键 + 在Unix的land shell中。例如,

    #include <stdio.h>
    #include <unistd.h>     // read
    
    void shell()
    {
        char line[256];
        for( bool finished = false; not finished; )
        {
            printf( ">>> " );
            //fgets( line, sizeof( line ), stdin );
    
            fflush( stdout );
            const int n_bytes = read( 0, line, sizeof( line ) - 1 );
            line[n_bytes] = '\0';
    
            char const* p = line;
            finished = true;
            while( char const input = *p++ )
            { 
                if( input == '\n' )
                {
                    finished = false;
                    break;
                } 
                printf( "[%c]", input );
            }
            printf( "\n" );
        }
    }
    
    auto main()
        -> int
    {
        printf( "before shell\n" );
        shell();
        printf( "shell has exited\n" );
    }
    

    请您解决以下问题:

    • 处理EOF(空行按下)。
    • 重写C++ C++流,而不是C FILE* 输入/输出。
    • 用一个 Ctrl键 + -按下输入行控制台输出中缺少换行符。

    注1: read 通常也可用于Windows编译器。然而,

    注2: Ctrl键 + 推动当前行是一个Unix的land约定。如果你想让你的程序表现出这种行为,不管它是如何运行或在什么系统上运行的,你必须使用一些可移植的低级字符输入库,比如ncurses。