Reputation: 2214
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::string. I have tried something like
char *sResult = (char*)malloc(1024);
std:string line;
line= line+ sResult
Thanks and regards, Sam
Upvotes: 2
Views: 11608
Reputation: 6389
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.
Upvotes: 0
Reputation: 6353
Try this: char* ptrToString = "wharever"; std::string szMyStdString = ptrToStrin
g
Upvotes: 0
Reputation: 506837
If you have a line of data that isn't necessarily a C-string, you use string's constructor
std::string s(sResult, sSize);
Upvotes: 1
Reputation: 132974
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
Upvotes: 9
Reputation: 15969
The std::string class has a constructor taking a const char *
so you can do
char *foo;
/* .... initialize foo ... */
std::string some_string(foo);
Upvotes: 1