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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With