Swift 中的 getch() 等效项:从标准输入中读取单个字符而无需换行 [英] getch() equivalent in Swift: read a single character from stdin without a newline

查看:84
本文介绍了Swift 中的 getch() 等效项:从标准输入中读取单个字符而无需换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找像 getch() 这样的 Swift 函数 从 C 从终端输入读取单个字符,而无需用户按回车键.getchar()readLine() 是不够的,因为它们都需要返回.

I'm looking for a Swift function like getch() from C to read a single character from terminal input without requiring the user to press the return key. getchar() and readLine() are not sufficient, as they both require return.

ncurses 有一个 getch() 函数看起来很有希望,但不幸的是似乎需要接管整个窗口的显示.

There's a getch() function from ncurses which looked promising, but unfortunately seems to require taking over the display of the whole window.

推荐答案

在网上搜索了一段时间后,我登陆了以下(部分基于 这个答案):

After searching for a while online, I landed on the following (partly based on this answer):

import Foundation

extension FileHandle {
    func enableRawMode() -> termios {
        var raw = termios()
        tcgetattr(self.fileDescriptor, &raw)

        let original = raw
        raw.c_lflag &= ~UInt(ECHO | ICANON)
        tcsetattr(self.fileDescriptor, TCSADRAIN, &raw)
        return original
    }

    func restoreRawMode(originalTerm: termios) {
        var term = originalTerm
        tcsetattr(self.fileDescriptor, TCSADRAIN, &term)
    }
}

func getch() -> UInt8 {
    let handle = FileHandle.standardInput
    let term = handle.enableRawMode()
    defer { handle.restoreRawMode(originalTerm: term) }

    var byte: UInt8 = 0
    read(handle.fileDescriptor, &byte, 1)
    return byte
}

fputs("Press any key to continue... ", stdout)
fflush(stdout)

let x = getch()
print()
print("Got character: \(UnicodeScalar(x))")

这篇关于Swift 中的 getch() 等效项:从标准输入中读取单个字符而无需换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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