2012-01-17 94 views
4

我希望我在这里不要求太多。在Objective-C中编写一个命令行工具,它接受输入,清除屏幕然后输出

我想创建一个命令行工具,它将在终端窗口中运行。它将从终端获取输入,对字符串进行一些操作,清除屏幕然后输出字符串。

#import <Foundation/Foundation.h> 
#include <stdlib.h> 

int main (int argc, const char *argv[]) 
{  
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    NSLog (@"Running...."); 

     // take the argument as an NSString 
     // do something with the NSString. 
     // clear the terminal screen. 
     // output the manipulated screen. 

    [pool drain]; 
    return 0; 

} 

这可能吗?有小费吗?我想尽可能在​​Objective-C中编码。

感谢,

EDIT 1 *

只是要清楚,我想连续输入和程序输出。换句话说,在可执行文件开始运行之后,有必要输入数据。不只是最初执行时。

+0

你总是可以调用'EXEC( “在/ usr/bin中/清除”);'清屏。要接受输入,可以使用任何C或C++方法,例如'fscanf()'或'std :: cin'。 – user1118321 2012-01-17 14:29:56

回答

4

这是可能的。在创建项目时使用Xcode中的“命令行工具”模板。

一个简单的例子可以是:

#import <Foundation/Foundation.h> 

int main (int argc, const char * argv[]) 
{ 
    @autoreleasepool { 
     char input[50]; 
     while (true) { 
      // take the argument as an NSString 
      NSLog(@"Enter some text please: "); 
      fgets(input, sizeof input, stdin); 
      NSString *argument = [[NSString stringWithCString:input encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 

      // do something with the NSString. 
      NSString *uppercase = [argument uppercaseString]; 

      // clear the terminal screen. 
      system("clear"); 

      // output the manipulated screen. 
      NSLog(@"Hello, %@!", uppercase); 
     } 
    } 
    return 0; 
} 
相关问题