开发者

Conversion of char * to string

开发者 https://www.devze.com 2023-02-01 08:57 出处:网络
Does anyone have an idea how to convert char* to string. Actually, I have a function which returns value as char*and now i need to store/copystd:开发者_StackOverflow:string.

Does anyone have an idea how to convert char* to string. Actually, I have a function which returns value as char* and now i need to store/copy std:开发者_StackOverflow:string. I have tried something like

char *sResult = (char*)malloc(1024); std:string line; line= line+ sResult

Thanks and regards, Sam


How about

std::string line(szResult);


There is an implicit conversion from const char* to std::string(via nonexplicit constructor). So the following will all work (suppose ch is const char* or char*)

std::string s (ch);
std::string s = ch;
s = ch;
f(ch); //where f is declared to take std::string
etc


The std::string class has a constructor taking a const char *so you can do

char *foo;
/* .... initialize foo ... */
std::string some_string(foo);


std:string line; line.append(sResult); or std::string line(sResult);


If you have a line of data that isn't necessarily a C-string, you use string's constructor

std::string s(sResult, sSize);


Try this: char* ptrToString = "wharever"; std::string szMyStdString = ptrToString


First of all you need to type to colons for the scope specifier like so:

std::string line;

And then depending on the C library you are using the + operator might not be overloaded to handle char* string so you should be better of using:

line = line + std::string(sResult);

Though your implementation, should work if you fix the scope specifier, in full-featured c++ standard library implementations like ms or gcc ones.

0

精彩评论

暂无评论...
验证码 换一张
取 消