41

是否有类似于 C 的 Go 函数getchar能够在控制台中处理制表符?我想在我的控制台应用程序中完成某种完成。

4

6 回答 6

22

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')。

但是,对于您的需要(检测选项卡),Cgetchar()不适合,因为它需要用户按 Enter。你需要的是像 @miku 提到的 ncurses 的 getch()/readline/jLine 之类的东西。有了这些,您实际上就在等待一个按键。

所以你有多种选择:

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

  2. 滚动您自己的起点,请参见http://play.golang.org/p/plwBIIYiqG

  3. 用于os.Exec运行 stty 或 jLine。

参考:

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

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

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

于 2012-12-31T06:32:47.127 回答
15

假设您想要无缓冲的输入(无需按回车键),这可以在 UNIX 系统上完成:

package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    // disable input buffering
    exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()
    // do not display entered characters on the screen
    exec.Command("stty", "-F", "/dev/tty", "-echo").Run()
    // restore the echoing state when exiting
    defer exec.Command("stty", "-F", "/dev/tty", "echo").Run()

    var b []byte = make([]byte, 1)
    for {
        os.Stdin.Read(b)
        fmt.Println("I got the byte", b, "("+string(b)+")")
    }
}
于 2013-06-24T15:04:00.110 回答
7

感谢 Paul Rademacher - 这有效(至少在 Mac 上):

package main

import (
    "bytes"
    "fmt"

    "github.com/pkg/term"
)

func getch() []byte {
    t, _ := term.Open("/dev/tty")
    term.RawMode(t)
    bytes := make([]byte, 3)
    numRead, err := t.Read(bytes)
    t.Restore()
    t.Close()
    if err != nil {
        return nil
    }
    return bytes[0:numRead]
}

func main() {
    for {
        c := getch()
        switch {
        case bytes.Equal(c, []byte{3}):
            return
        case bytes.Equal(c, []byte{27, 91, 68}): // left
            fmt.Println("LEFT pressed")
        default:
            fmt.Println("Unknown pressed", c)
        }
    }
    return
}
于 2016-04-24T21:46:10.653 回答
5

这里的其他答案建议如下:

  • 使用 cgo

  • os.Execstty

    • 不便携
    • 效率低下
    • 容易出错
  • 使用使用的代码/dev/tty

    • 不便携
  • 使用 GNU readline 包

    • 如果它是 C readline 的包装器或使用上述技术之一实现,则效率低下
    • 否则还可以

但是,对于简单的情况,只需使用来自Go 项目的 Sub-repositories的包就很容易了。

基本上,使用terminal.MakeRawandterminal.Restore将标准输入设置为原始模式(检查错误,例如,如果 stdin 不是终端);那么您可以直接从 读取字节os.Stdin,或者更有可能通过 a读取字节bufio.Reader(为了提高效率)。

例如,像这样:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"

    "golang.org/x/crypto/ssh/terminal"
)

func main() {
    // fd 0 is stdin
    state, err := terminal.MakeRaw(0)
    if err != nil {
        log.Fatalln("setting stdin to raw:", err)
    }
    defer func() {
        if err := terminal.Restore(0, state); err != nil {
            log.Println("warning, failed to restore terminal:", err)
        }
    }()

    in := bufio.NewReader(os.Stdin)
    for {
        r, _, err := in.ReadRune()
        if err != nil {
            log.Println("stdin:", err)
            break
        }
        fmt.Printf("read rune %q\r\n", r)
        if r == 'q' {
            break
        }
    }
}

于 2019-08-07T15:09:21.817 回答
0

1-您可以使用C.getch()

这适用于 Windows 命令行,只读取一个字符而不输入:(
在 shell(终端)内运行输出二进制文件,而不是在管道或编辑器内。)

package main

//#include<conio.h>
import "C"

import "fmt"

func main() {
    c := C.getch()
    fmt.Println(c)
}

2- 对于 Linux(在 Ubuntu 上测试):

package main

/*
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
char getch(){
    char ch = 0;
    struct termios old = {0};
    fflush(stdout);
    if( tcgetattr(0, &old) < 0 ) perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if( tcsetattr(0, TCSANOW, &old) < 0 ) perror("tcsetattr ICANON");
    if( read(0, &ch,1) < 0 ) perror("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if(tcsetattr(0, TCSADRAIN, &old) < 0) perror("tcsetattr ~ICANON");
    return ch;
}
*/
import "C"

import "fmt"

func main() {
    fmt.Println(C.getch())
    fmt.Println()
}

请参阅:
Linux 中与 getch() 和 getche() 等效的是什么?
为什么我在 Linux 上找不到 <conio.h>?


3-这也有效,但需要“输入”:

package main

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

func main() {
    r := bufio.NewReader(os.Stdin)
    c, err := r.ReadByte()
    if err != nil {
        panic(err)
    }
    fmt.Println(c)
}
于 2016-05-29T03:41:23.460 回答
-4

您还可以使用 ReadRune:

reader := bufio.NewReader(os.Stdin)
// ...
char, _, err := reader.ReadRune()
if err != nil {
    fmt.Println("Error reading key...", err)
}

符文类似于字符,因为 GoLang 并没有真正的字符,为了尝试和支持多种语言/unicode/等。

于 2017-05-14T14:47:16.243 回答