将char *转换为字符串
有没有人知道如何将char *转换为字符串。 实际上,我有一个函数,它返回值为char *,现在我需要存储/复制std :: string。 我尝试过类似的东西
char *sResult = (char*)malloc(1024); std:string line; line= line+ sResult
谢谢,问候,山姆
怎么样
std::string line(szResult);
有一个从const char*
到std::string
的隐式转换 (通过非显式构造函数)。 所以以下都可以工作(假设ch是const char*
或char*
)
std::string s (ch); std::string s = ch; s = ch; f(ch); //where f is declared to take std::string etc
std :: string类有一个构造函数采用const char *
所以你可以这样做
char *foo; /* .... initialize foo ... */ std::string some_string(foo);
std:string line; line.append(sResult); 或std :: string line(sResult);
如果您有一行不一定是C字符串的数据,则使用字符串的构造函数
std::string s(sResult, sSize);
试试这个: char* ptrToString = "wharever"; std::string szMyStdString = ptrToStrin
char* ptrToString = "wharever"; std::string szMyStdString = ptrToStrin
g
首先,您需要为范围说明符键入冒号,如下所示:
std :: string line;
然后根据您使用+运算符的C库,可能不会重载以处理char * string,因此您应该更好地使用:
line = line + std :: string(sResult) ;
虽然您的实现,如果您修复了范围说明符,应该可以在全function的c ++标准库实现中使用,例如ms或gcc。