Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert std::string to NSString?

Hi I am trying to convert a standard std::string into an NSString but I'm not having much luck.

I can convert successfully from an NSString to a std::string with the following code

NSString *realm = @"Hollywood"; std::string REALM = [realm cStringUsingEncoding:[NSString defaultCStringEncoding]]; 

However I get a compile time error when I try the following

NSString *errorMessage = [NSString stringWithCString:REALM encoding:[NSString defaultCStringEncoding]]; 

The error I get is

Cannot convert 'std::string' to 'const char*' in argument passing 

Am I missing something here?

Thanks in advance.

like image 357
Anthony McCormick Avatar asked Aug 23 '10 22:08

Anthony McCormick


People also ask

How do you convert STD string to Lpwstr?

std::wstring stemp = std::wstring(s. begin(), s. end()); LPCWSTR sw = stemp. c_str();

How do I append to NSString?

Working with NSString. Instances of the class NSString are immutable – their contents cannot be changed. Once a string has been initialized using NSString, the only way to append text to the string is to create a new NSString object. While doing so, you can append string constants, NSString objects, and other values.

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.


1 Answers

Get c-string out of std::string for conversion:

NSString *errorMessage = [NSString stringWithCString:REALM.c_str()                                     encoding:[NSString defaultCStringEncoding]]; 
like image 192
Vladimir Avatar answered Sep 18 '22 07:09

Vladimir