Search code examples
objective-cnsstringobjective-c++stdstring

Converting NSString to std::string


I try to pass a NSString to a C++ function, but I only get the first letter. Here is the code:

#import <Foundation/Foundation.h>
#import <string>
int main(int argc, const char * argv[])
{

@autoreleasepool {
    NSString* objcString=@"test";
    std::string cppString([objcString cStringUsingEncoding:NSUnicodeStringEncoding]);
    NSLog(@"%@, %s",objcString, cppString.c_str()
          );

}
return 0;
}

It gives me:

2013-03-05 10:22:15.362 TEST[1136:353] test, t

Thank for your time, have a good day.


Solution

  • The encoding is wrong. NSUnicodeStringEncoding returns an UTF-16 string. The characters "t, e, s, t" fit in one byte - so in UTF-16, they're represented by a non-zero byte and a zero byte. The zero tells NSLog() that it's the end of the string. Use NSUTF8StringEncoding instead.