samprat
samprat

Reputation: 2214

Conversion of char * to 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::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

Answers (7)

Shinnok
Shinnok

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

Sandy
Sandy

Reputation: 6353

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

Upvotes: 0

Johannes Schaub - litb
Johannes Schaub - litb

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

Armen Tsirunyan
Armen Tsirunyan

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

hB0
hB0

Reputation: 2037

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

Upvotes: 1

johannes
johannes

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

kellogs
kellogs

Reputation: 2857

How about

std::string line(szResult);

Upvotes: 8

Related Questions