Reputation:
How can I get input from the console in Objective C? My concern is to avoid the possibility of buffer overflows, which is why I want to steer clear of gets()
and scanf()/sscanf()
. From searching StackOverflow, that's all I've been seeing. Is scanf()
more secure in Objective C to the extent that I wouldn't have to worry?
Just recently, I found this example: I like it; but is there already a class for such?
printf("What is your name?");
NSFileHandle *input = [NSFileHandle fileHandleWithStandardInput];
NSData *inputData = [NSData dataWithData:[input availableData]];
NSString *inputString = [[NSString alloc] initWithData:inputData
encoding:NSUTF8StringEncoding];
inputString = [inputString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
printf("Hello %s.n",[inputString UTF8String]);
Upvotes: 0
Views: 599
Reputation: 53000
The standard C I/O functions can be used, as you indicate. They are not more secure just because you are using Objective-C. To avoid buffer overflow issues use fgets
rather and gets
. Note you will be reading a C-style string and will need to convert it if you need an NSString
.
At the Cocoa level you can use NSFileHandle
as you show. Note that availableData
returns all the available data not the next line, but as the console device is usually set to line mode what will be returned is the next line provided the user has not typed ahead.
At a lower level you can look at read
.
HTH
Upvotes: 1