I test you code in command line `swiftc main.swift` and in macOS Command
Line Tool app.
Here is the main.swift:
import Foundation
import Foundation
func input() -> String {
let keyboard = FileHandle.standardInput
let inputData = keyboard.availableData
let strData = String(data: inputData, encoding: .utf8)
return strData!
}
func write(_ txt: String) {
print(txt, terminator: "")
}
func read() -> String {
let c = CharacterSet.whitespacesAndNewlines
return input().trimmingCharacters(in: c)
}
/* main program */
write("Enter your name: ")
let s = read()
print("You name is \(s)")
It turns out that the input request was ran before the `write("Enter your
name: ")`. I don't why. Maybe it is a bug?
Here is my output in terminal:
$ swiftc main.swift
$ ./main
abc
Enter your name: You name is abc
$
As you can see, the program asked me to input my name before it showed the
notification. In playground, the situation is alike.
However, if the code is running as a command line tool, created by Xcode ->
Create a new project -> macOS, command line tool, everything works fine.
Zhaoxin
···
On Sun, Sep 18, 2016 at 9:16 PM, Mr Bee via swift-users < swift-users@swift.org> wrote:
Hi all,
Another question. I used to use this snippet to read keyboard input from
XCode's Playground. And it used to work very well. Today, I just updated my
XCode to v.8 and Swift v.3. After a little bit modification here and there
due to Swift 3 incompatibility, I got this code compiled without error. But
it doesn't work. No keyboard input is taken. It just stucks.
Here's the code:
import Foundation
func input() -> String {
let keyboard = FileHandle.standardInput
let inputData = keyboard.availableData
let encoding = String.Encoding(rawValue: String.Encoding.utf8.rawValue)
let strData = String(data: inputData, encoding: encoding)
return strData! as String
}
func write(_ txt: String) {
print(txt, terminator: "")
}
func read() -> String {
let c = CharacterSet.whitespacesAndNewlines
return input().trimmingCharacters(in: c)
}
/* main program */
write("Enter your name: ")
let s = read()
So, does anyone know how to make it works (again)? Thank you.
Regards,
–Mr Bee
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users