1

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.

impact27
  • 497
  • 4
  • 14

4 Answers4

2

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.

1

How about:

std::string cppString([objcString UTF8String]);
trojanfoe
  • 118,129
  • 19
  • 204
  • 237
0

I do it ubiquitously in my code with NSUTF8Encoding instead that NSUnicodeEncoding.

Jack
  • 128,551
  • 28
  • 227
  • 331
0

I think this answer might help you: How do I convert a NSString into a std::string?

For integrity:

NSString *foo = @"Foo";
std::string *bar = new std::string([foo UTF8String]);
Community
  • 1
  • 1
o15a3d4l11s2
  • 3,850
  • 3
  • 26
  • 39