如何在Objective-C中从键盘读取输入 [英] How to read input from the keyboard in Objective-C
问题描述
我正在编写一个从键盘获取输入的程序,我想知道是否有任何方法可以从键盘获取输入并将其存储在NSString
对象中.
Hi I am making a program that gets input from the keyboard and I was wondering if there was any way to get input from the keyboard and store it in an NSString
object.
推荐答案
如果您是作为命令行应用程序执行此操作,那么这是我上周编写的代码,用于从命令提示符处获得一行(我将其设置为NSString
类别):
If you are doing this as a command-line app, then here's code I wrote last week to get a line from the command prompt (I made it an NSString
category):
+ (NSString *) stringFromStandardInDelimitedByCharactersInSet:(NSCharacterSet *)delimiters {
NSMutableString * string = [NSMutableString string];
unichar input = '\0';
while (input = getchar()) {
if ([delimiters characterIsMember:input]) { break; }
[string appendFormat:@"%C", input];
}
return string;
}
然后我会像这样使用它:
And then I'd use it like this:
NSString * input = [NSString stringFromStandardInDelimitedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
它不能很好地处理unicode字符(尽管使用unichar),因为getchar()仅返回常规char.但是,对于基本的命令行文本输入,它工作得很好.但是,请注意,这将阻塞执行它的线程(因为getchar()是阻塞调用).
It doesn't handle unicode characters very well (despite using a unichar), because getchar() only returns a regular char. However, for basic command-line text entry, it works pretty well. However, be warned that this will block the thread on which it's executed (since getchar() is a blocking call).
这篇关于如何在Objective-C中从键盘读取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!