ios - 在 Swift 中重新创建 Python 的输入语句

标签 ios swift

我试图在 Swift 中重新创建 Python 的 input() 语句,我看到了一些例子,但我试图让它变得更好,首先,我的版本删除了 \n 字符串的一部分,另外,我试图让它首先打印一个提示,这样 var example = input() 就会等待消息,(它确实如此),但是然后 var example = input("Enter text: ") 将打印 Enter text: 并等待输入文本。

问题是,swift 似乎打乱了打印顺序。比如正代码:

import Foundation

func input(inputStatement: String? = nil) -> String {
    if let inputStatement = inputStatement {
        print(inputStatement, terminator:"")
    }
    let keyboard = NSFileHandle.fileHandleWithStandardInput()
    let inputData = keyboard.availableData
    var strData = NSString(data: inputData, encoding: NSUTF8StringEncoding) as! String
    strData = strData.stringByReplacingOccurrencesOfString("\n", withString: "")
    print()
    return strData
}

print("Creating the input statement in Swift!")
var test = input("What's your name: ")
print("You entered: \(test).")

输入文本“hi”,打印:

Creating the input statement in Swift!
hi
What's your name: You entered: hi.

我期望的是:

Creating the input statement in Swift!
What's your name: hi
You entered: hi.

我在这里错过了什么?

谢谢

最佳答案

问题是标准输出文件描述符是行缓冲 写入终端时(否则完全缓冲)。 因此输出

print(inputStatement, terminator:"")

之前被缓冲并且不被写入
print()

写一个换行符。您可以通过刷新文件来解决这个问题 明确描述符:

if let inputStatement = inputStatement {
    print(inputStatement, terminator:"")
    fflush(stdout)
}

还要注意有一个

public func readLine(stripNewline stripNewline: Bool = default) -> String?

从标准输入中读取一行,可以选择 删除尾随的换行符。这个功能还有 刷新标准输出。因此,一个更简单的实现是

func input(prompt: String = "") -> String {
    print(prompt, terminator: "")
    guard let reply = readLine(stripNewline: true) else {
        fatalError("Unexpected EOF on input")
    }
    return reply
}

(当然,您可以选择以不同方式处理“文件结尾”。)

关于ios - 在 Swift 中重新创建 Python 的输入语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675068/

相关文章:

ios 应用程序崩溃,没有日志

ios - 如何修复 "App Store Connect Operation ERROR ITMS-90771"

iOS NSNotificationCenter 观察者未被删除

ios - Xcode 错误 : Could not launch app - unable to attach

ios - 如何将核心数据模型项传递到 View 中进行编辑

android - 使用 React Native 更改键盘后面的背景颜色?

ios - 我可以在 Swift 5 和 IOS 12 中以编程方式更改 iOS 屏幕壁纸吗

ios - Firebase 和 Stripe : Storing users credit card information

ios - 无法在 Swift spritekit 应用程序中显示 LaunchScreen 图像

ios - 将 TextView 限制为 swift 2 中的特定行数