与getchar类似的功能 [英] function similar to getchar

查看:218
本文介绍了与getchar类似的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个类似于C的 getchar 的Go功能能够处理控制台中的Tab键?我想在控制台应用程序中完成某种操作。

Is there a Go function similar to C's getchar able to handle tab press in console? I want to make some sort of completion in my console app.

推荐答案

C的 getchar()示例:

#include <stdio.h>
void main()
{
    char ch;
    ch = getchar();
    printf("Input Char Is :%c",ch);
}

等效项:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {

    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('\n')

    fmt.Printf("Input Char Is : %v", string([]byte(input)[0]))

    // fmt.Printf("You entered: %v", []byte(input))
}

最后评论这行代码仅显示当您按下 tab 时,第一个元素是U + 0009('CHARACTER TABULATION')。

The last commented line just shows that when you press tab the first element is U+0009 ('CHARACTER TABULATION').

但是,出于您的需要(检测选项卡),C的 getchar()不适合,因为它要求用户点击输入。您需要的是@miku提到的ncurses的getch()/ readline / jLine之类的东西。有了这些,您实际上可以等待一次击键。

However for your needs (detecting tab) C's getchar() is not suitable as it requires the user to hit enter. What you need is something like ncurses' getch()/ readline/ jLine as mentioned by @miku. With these, you actually wait for a single keystroke.

因此,您有多种选择:


  1. 使用 ncurses / readline 绑定,例如 https://code.google.com/p/goncurses/ 或类似的内容,例如 https://github.com/nsf/termbox

  1. Use ncurses / readline binding, for example https://code.google.com/p/goncurses/ or equivalent like https://github.com/nsf/termbox

滚动自己的语言,请参见 http://play.golang.org/p/plwBIIYiqG

Roll your own see http://play.golang.org/p/plwBIIYiqG for starting point

使用 os.Exec 运行stty或jLine。

use os.Exec to run stty or jLine.

裁判:

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/zhBE5MH4n-Q

https://groups.google.com/forum/?fromgroups =#!到pic / golang-nuts / S9AO_kHktiY

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/icMfYF8wJCk

这篇关于与getchar类似的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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