Question

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.

Was it helpful?

Solution

NSString does not have a stringWithBytes:length:encoding: class method, but you can use

NSString* word2 = [[NSString alloc] initWithBytes:word
                                         length:nChars
                                       encoding:NSUTF8StringEncoding];

Note however, that scanf() returns the number of scanned items and not the number of scanned characters. So nChars will contain 1 and not the string length, so you should set nChars = strlen(word) instead.

A simpler alternative is (as also mentioned in one answer to the linked question)

NSString* word2 = [NSString stringWithUTF8String:word];

OTHER TIPS

NSString does not respond to the selector stringWithBytes:length:encoding:. You probably wanted initWithBytes:length:encoding:.

Story in short: you might want to consider a const char C-string suitable initializer for your NSString object. Also, allocate memory before sending any initializer message to the NSString object. I would expect something like:

char word[40];
int nChars = scanf("%39s", word);

NSString *word2 = [[NSString alloc] initWithCString:word encoding:NSASCIIStringEncoding];

Note that initWithCString per design only supports properly null '\0' terminated 8-bit character arrays. For unterminated bytes arrays you have initWithBytes:length:encoding: instead.

For Unicode characters you could consider initWithCharactersNoCopy:length:freeWhenDone:.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top