Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a const char * to std::string [duplicate]

Tags:

c++

What is the correct/best/simplest way to convert a c-style string to a std::string.

The conversion should accept a max_length, and terminate the string at the first \0 char, if this occur before max_length charter.

like image 812
Allan Avatar asked Nov 14 '11 18:11

Allan


People also ask

Can you assign a const char * to a string?

You absolutely can assign const char* to std::string , it will get copied though. The other way around requires a call to std::string::c_str() .

Can const char * Be Changed?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.


2 Answers

This page on string::string gives two potential constructors that would do what you want:

string ( const char * s, size_t n ); string ( const string& str, size_t pos, size_t n = npos ); 

Example:

#include<cstdlib> #include<cstring> #include<string> #include<iostream> using namespace std;  int main(){      char* p= (char*)calloc(30, sizeof(char));     strcpy(p, "Hello world");      string s(p, 15);     cout << s.size() << ":[" << s << "]" << endl;     string t(p, 0, 15);     cout << t.size() << ":[" << t << "]" << endl;      free(p);     return 0; } 

Output:

15:[Hello world] 11:[Hello world] 

The first form considers p to be a simple array, and so will create (in our case) a string of length 15, which however prints as a 11-character null-terminated string with cout << .... Probably not what you're looking for.

The second form will implicitly convert the char* to a string, and then keep the maximum between its length and the n you specify. I think this is the simplest solution, in terms of what you have to write.

like image 92
Vlad Avatar answered Oct 03 '22 08:10

Vlad


std::string str(c_str, strnlen(c_str, max_length)); 

At Christian Rau's request:

strnlen is specified in POSIX.1-2008 and available in GNU's glibc and the Microsoft run-time library. It is not yet found in some other systems; you may fall back to Gnulib's substitute.

like image 30
ephemient Avatar answered Oct 03 '22 08:10

ephemient