Input from the keyboard in command line applicatio

2019-01-04 07:00发布

I am attempting to get the keyboard input for a command line app for the new Apple programming language Swift.

I've scanned the docs to no avail.

import Foundation

println("What is your name?")
???

Any ideas?

16条回答
走好不送
2楼-- · 2019-01-04 07:43

Another alternative is to link libedit for proper line editing (arrow keys, etc.) and optional history support. I wanted this for a project I'm starting and put together a basic example for how I set it up.

Usage from swift

let prompt: Prompt = Prompt(argv0: C_ARGV[0])

while (true) {
    if let line = prompt.gets() {
        print("You typed \(line)")
    }
}

ObjC wrapper to expose libedit

#import <histedit.h>

char* prompt(EditLine *e) {
    return "> ";
}

@implementation Prompt

EditLine* _el;
History* _hist;
HistEvent _ev;

- (instancetype) initWithArgv0:(const char*)argv0 {
    if (self = [super init]) {
        // Setup the editor
        _el = el_init(argv0, stdin, stdout, stderr);
        el_set(_el, EL_PROMPT, &prompt);
        el_set(_el, EL_EDITOR, "emacs");

        // With support for history
        _hist = history_init();
        history(_hist, &_ev, H_SETSIZE, 800);
        el_set(_el, EL_HIST, history, _hist);
    }

    return self;
}

- (void) dealloc {
    if (_hist != NULL) {
        history_end(_hist);
        _hist = NULL;
    }

    if (_el != NULL) {
        el_end(_el);
        _el = NULL;
    }
}

- (NSString*) gets {

    // line includes the trailing newline
    int count;
    const char* line = el_gets(_el, &count);

    if (count > 0) {
        history(_hist, &_ev, H_ENTER, line);

        return [NSString stringWithCString:line encoding:NSUTF8StringEncoding];
    }

    return nil;
}

@end
查看更多
等我变得足够好
3楼-- · 2019-01-04 07:45

Here is simple example of taking input from user on console based application: You can use readLine(). Take input from console for first number then press enter. After that take input for second number as shown in the image below:

func solveMefirst(firstNo: Int , secondNo: Int) -> Int {
    return firstNo + secondNo
}

let num1 = readLine()
let num2 = readLine()

var IntNum1 = Int(num1!)
var IntNum2 = Int(num2!)

let sum = solveMefirst(IntNum1!, secondNo: IntNum2!)
print(sum)

Output

查看更多
孤傲高冷的网名
4楼-- · 2019-01-04 07:51

Since there were no fancy solutions to this problem, I made a tiny class to read and parse the standard input in Swift. You can find it here.

Example

To parse:

+42 st_ring!
-0.987654321 12345678900
.42

You do:

let stdin = StreamScanner.standardInput

if
    let i: Int = stdin.read(),
    let s: String = stdin.read(),
    let d: Double = stdin.read(),
    let i64: Int64 = stdin.read(),
    let f: Float = stdin.read()
{
    print("\(i) \(s) \(d) \(i64) \(f)")  //prints "42 st_ring! -0.987654321 12345678900 0.42"
}
查看更多
成全新的幸福
5楼-- · 2019-01-04 07:55

I just wanted to comment (I have not enough reps) on xenadu's implementation, because CChar in OS X is Int8, and Swift does not like at all when you add to the array when getchar() returns parts of UTF-8, or anything else above 7 bit.

I am using an array of UInt8 instead, and it works great and String.fromCString converts the UInt8 into UTF-8 just fine.

However this is how I done it

func readln() -> (str: String?, hadError: Bool) {
    var cstr: [UInt8] = []
    var c: Int32 = 0
    while c != EOF {
        c = getchar()
        if (c == 10 || c == 13) || c > 255 { break }
        cstr.append(UInt8(c))
    }
    cstr.append(0)
    return String.fromCStringRepairingIllFormedUTF8(UnsafePointer<CChar>(cstr))
}

while true {
    if let mystring = readln().str {
        println(" > \(mystring)")
    }
}
查看更多
登录 后发表回答