I am attempting to use scanf to assign a value to an NSString, as per the answers to this question by Omar. This is the code, taken straight from progrmr's answer:
char word[40];
int nChars = scanf("%39s", word); // read up to 39 chars (leave room for NUL)
NSString* word2 = [NSString stringWithBytes:word
length:nChars
encoding:NSUTF8StringEncoding];
However, I'm getting an error on the last line that makes absolutely no sense to me:
No known class method for selector 'stringWithBytes:length:encoding:'
What in the world could be causing this error?
And yes, I do have #import <Foundation/Foundation.h>
at the top of the file.
NSString
does not have astringWithBytes:length:encoding:
class method, but you can useNote however, that
scanf()
returns the number of scanned items and not the number of scanned characters. SonChars
will contain1
and not the string length, so you should setnChars = strlen(word)
instead.A simpler alternative is (as also mentioned in one answer to the linked question)