Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C how to read data from standard input and ignore extra (unneeded) characters

Tags:

objective-c

I am currently using the following code to read the first character from the standard input (after a prompt):

NSFileHandle *stdIn = [NSFileHandle fileHandleWithStandardInput];
    NSString* input = [[NSString alloc]
        initWithData:[stdIn readDataOfLength:1]
        encoding:NSUTF8StringEncoding];

However, after the program completes, all the extra characters get interpreted by the command line (bash, in this case). For example, the prompt is

File already exists, do you want to overwrite it? [y/N]

and if I input noooooo, bash says -bash: oooooo: command not found after the program finishes. How do I avoid this? Using [stdIn readDataToEndOfFile] does not work, expectedly.

I could use [stdIn readToEndOfFileInBackgroundAndNotify], but if I need to get user input from such a prompt again, it wouldn't be possible.

like image 494
bladerunner1992 Avatar asked Dec 01 '22 20:12

bladerunner1992


1 Answers

If you want to keep it strictly in Objective C, you can always do:

NSFileHandle *kbd = [NSFileHandle fileHandleWithStandardInput];
NSData *inputData = [kbd availableData];
NSString *option = [[[NSString alloc] initWithData:inputData 
                 encoding:NSUTF8StringEncoding] substringToIndex:1];
NSLog(@"%@",option);
like image 83
fiacobelli Avatar answered Jan 08 '23 13:01

fiacobelli