impact27
impact27

Reputation: 537

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.

Upvotes: 2

Views: 6818

Answers (4)

user529758
user529758

Reputation:

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.

Upvotes: 2

o15a3d4l11s2
o15a3d4l11s2

Reputation: 4059

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]);

Upvotes: 0

Jack
Jack

Reputation: 133619

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

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122458

How about:

std::string cppString([objcString UTF8String]);

Upvotes: 1

Related Questions