Read input from a cocoa/foundation tool console?

时间秒杀一切 提交于 2019-12-18 04:26:09

问题


I wonder if Objective-C/Foundation has any special commands for reading user input from the console. Since it has NSLog for output maybe there is something else I could use instead of the scanf command.

I need to read some numbers (user input) into my tool. What is the best way to get these input in types like double or int? And how do I get user input into an NSString?


回答1:


I was bored earlier and came across this issue of 'use scanf'. since I wanted to see if I could do it without dropping into c, the following came up:

NSFileHandle *input = [NSFileHandle fileHandleWithStandardInput];
while (1)
{
    NSData* data = [input availableData];
    if(data != nil)
    {    
        NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
 }

I'm sure somebody could optimize this and make it nicer (this was used for a really simple PoC CLI tool)




回答2:


The only real Cocoa support for input is NSFileHandle's fileHandleWithStandardInput. It isn't really more useful than scanf() if you ask me. But for getting input into specific types, well, that's pretty much NSFormatter's thing. There are already a lot of predefined formatter types for standard things, and you can make a custom formatter if you have more specialized needs. So if you need something a little more than scanf(), just read in the data (either as bytes with scanf() or data with NSFileHandle) and make an NSString from it and you can format it to your heart's content.




回答3:


Nothing like scanf (which is a good thing). You can slurp data from stdin using NSFileHandle; for interactive input, fgets is better. You'll then want to use either strtol/strtoul/strtod, NSScanner, or NSNumberFormatter to convert the input to numeric types.



来源:https://stackoverflow.com/questions/869802/read-input-from-a-cocoa-foundation-tool-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!