473,578 Members | 3,102 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Conversion from std::string to char *, is there a better way?

I'm re-evaluating the way that I convert from a std::string to char *.
(Requirement: the source is a std::string, the usable contents are char *)

Here is what I've come up with:

#include <string>
#include <vector>
#include <cstring>

// presume s from somewhere, such as:
std::string s = "<initial value>";

std::vector<cha r> v(s.length() + 1);
std::strcpy(&v[0], s.c_str());
char * c = &v[0];
// use c, where a char * is _specifically_ required
s = c;

The above:
- doesn't use any pointers that must be manually deallocated
- is 100% portable(?)
- is 100% conformant(?)

I've seen Bjarne's similar implementation, but it uses new char * instead of
vector (obviously written before the STL was adopted).

auto_ptr<char> in place of vector<char> doesn't work because it doesn't handle
arrays.

Does anyone have comments on the above, specifically as to its suitability for
the requirements defined?
Jul 22 '05 #1
24 11015
On Thu, 10 Jun 2004 10:48:33 -0700, Julie <ju***@nospam.c om> wrote:
I'm re-evaluating the way that I convert from a std::string to char *.
(Requirement : the source is a std::string, the usable contents are char *)

Here is what I've come up with:

#include <string>
#include <vector>
#include <cstring>

// presume s from somewhere, such as:
std::string s = "<initial value>";

std::vector<cha r> v(s.length() + 1);
std::strcpy(&v[0], s.c_str());
char * c = &v[0];
Might be a good idea to use parentheses (i.e.: &(v[0]) instead of
&v[0] here) ... I can never remember the order of the operator
precedence.
// use c, where a char * is _specifically_ required
s = c;

The above:
- doesn't use any pointers that must be manually deallocated
- is 100% portable(?)
- is 100% conformant(?)

I've seen Bjarne's similar implementation, but it uses new char * instead of
vector (obviously written before the STL was adopted).

auto_ptr<cha r> in place of vector<char> doesn't work because it doesn't handle
arrays.

Does anyone have comments on the above, specifically as to its suitability for
the requirements defined?


Looks OK to me.

std::string::c_ str() will return a const char * pointing to the
string's character data which you can use to pass to functions which
expect constant pointers to zero-delimited C-style strings as
arguments. This is the simplest way to access the character data.

OTOH, if you have a function which expects a non-const char *, you
MUST copy the data from the constant buffer returned by c_str() to a
non-const buffer which you would generally allocate using "new
char[s.size()]", for example. It might be dangerous to cast away the
const if the function does anything but read the data (the behavior is
actually undefined by the standard).

Of course, your code would have to de-allocate the memory when done
with the buffer. I always use a smart pointer which can handle array
data (i.e. the destructor of the smart pointer calls "delete[]" and
not "delete"). The Boost library has such smart pointer templates. I
use one of my own which I adapted from code called the "grin pointer",
but the Boost library is expected to be incorporated into the next
version of the C++ standard.

The vector<char> is also a good solution, albeit one which might have
a bit more overhead (certainly not much, though) than using a simple
character array. Fortunately, the standard does guarantee that the
vector elements must be contiguous in memory, so assigning &(v[0]) to
a char * is OK.
--
Bob Hairgrove
No**********@Ho me.com
Jul 22 '05 #2
Julie wrote:
I'm re-evaluating the way that I convert from a std::string to char *.
(Requirement: the source is a std::string, the usable contents are char *)

Here is what I've come up with:

#include <string>
#include <vector>
#include <cstring>

// presume s from somewhere, such as:
std::string s = "<initial value>";

std::vector<cha r> v(s.length() + 1);
std::strcpy(&v[0], s.c_str());
char * c = &v[0];
// use c, where a char * is _specifically_ required
s = c;

The above:
- doesn't use any pointers that must be manually deallocated
- is 100% portable(?)
Looks like it
- is 100% conformant(?)
As soon as the requirement for contiguousness of 'std::vector' storage
makes it into the Standard (if it hasn't already) and trickles down to
all library implementations (if they haven't done it already to begin
with).

I've seen Bjarne's similar implementation, but it uses new char * instead of
vector (obviously written before the STL was adopted).
No, it was written before there was a suggestion that std::vector's
storage needs to be contiguous.
Does anyone have comments on the above, specifically as to its suitability for
the requirements defined?


AFAICT, the code is fine.

V
Jul 22 '05 #3
Victor Bazarov wrote:
- is 100% conformant(?)

As soon as the requirement for contiguousness of 'std::vector' storage
makes it into the Standard (if it hasn't already) and trickles down to
all library implementations (if they haven't done it already to begin
with).


Just to remove any uncertainty here, from Section 23.2.4/1 :

"The elements of a vector are stored contiguously, meaning that if v is
a vector<T, Allocator> where T is some type other than bool, then it
obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size()."
Alan
Jul 22 '05 #4
Bob Hairgrove wrote:
<snip>

OTOH, if you have a function which expects a non-const char *, you
MUST copy the data from the constant buffer returned by c_str() to a
non-const buffer which you would generally allocate using "new
char[s.size()]", for example. It might be dangerous to cast away the
const if the function does anything but read the data (the behavior is
actually undefined by the standard).


new char(s.size() + 1]
You need space for the nul char.

- Pete

<snip>
Jul 22 '05 #5
Alan Johnson wrote:
Victor Bazarov wrote:
- is 100% conformant(?)


As soon as the requirement for contiguousness of 'std::vector' storage
makes it into the Standard (if it hasn't already) and trickles down to
all library implementations (if they haven't done it already to begin
with).


Just to remove any uncertainty here, from Section 23.2.4/1 :

"The elements of a vector are stored contiguously, meaning that if v is
a vector<T, Allocator> where T is some type other than bool, then it
obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size()."


I take it, that's from the newer edition of the Standard, correct?
Is that ISO/IEC 14882-2003?

V
Jul 22 '05 #6
Julie,

If you make use of the fact that string is actually a vector, you can do the
following,
which follows somewhat your approach, but results in much simpler and few
lines of code,
and doesn't require the explicit inclusion of the vector template class.
Other than that, its exactly the same underlying idea you posted.

dave

#include <string>
#include <iostream>
using namespace std;

int foobar( char* s )
{
// do some nasty modifications to demonstrage non-const ness of s.
s[16]='d';
s[17]='o';
s[18]='g';

s[41]='f';
s[42]='o';
s[43]='x';

return 0;
}

int main( int argc, char* argv[])
{
string foo("the quick brown fox jumped over the lazy dog");
string bar(foo);
// modify the copy of the original string
char* c = &bar[0];
foobar(c);

cout << "original string is \"" << foo << "\"\n";
cout << "modified string is \"" <<bar<< "\"\n";
return 0;
}

"Julie" <ju***@nospam.c om> wrote in message
news:40******** *******@nospam. com...
I'm re-evaluating the way that I convert from a std::string to char *.
(Requirement: the source is a std::string, the usable contents are char *)

Here is what I've come up with:

#include <string>
#include <vector>
#include <cstring>

// presume s from somewhere, such as:
std::string s = "<initial value>";

std::vector<cha r> v(s.length() + 1);
std::strcpy(&v[0], s.c_str());
char * c = &v[0];
// use c, where a char * is _specifically_ required
s = c;

The above:
- doesn't use any pointers that must be manually deallocated
- is 100% portable(?)
- is 100% conformant(?)

I've seen Bjarne's similar implementation, but it uses new char * instead of vector (obviously written before the STL was adopted).

auto_ptr<char> in place of vector<char> doesn't work because it doesn't handle arrays.

Does anyone have comments on the above, specifically as to its suitability for the requirements defined?

Jul 22 '05 #7
(please don't top-post. rearranged.)
Dave Townsend wrote:

"Julie" <ju***@nospam.c om> wrote in message
news:40******** *******@nospam. com... <snip>
Julie,

If you make use of the fact that string is actually a vector, you can
do the following,
which follows somewhat your approach, but results in much simpler and
few lines of code,
and doesn't require the explicit inclusion of the vector template
class. Other than that, its exactly the same underlying idea you
posted.

dave

#include <string>
#include <iostream>
using namespace std;

int foobar( char* s )
{
// do some nasty modifications to demonstrage non-const ness of s.
s[16]='d';
s[17]='o';
s[18]='g';

s[41]='f';
s[42]='o';
s[43]='x';

return 0;
}

int main( int argc, char* argv[])
{
string foo("the quick brown fox jumped over the lazy dog");
string bar(foo);
// modify the copy of the original string
char* c = &bar[0];
foobar(c);

cout << "original string is \"" << foo << "\"\n";
cout << "modified string is \"" <<bar<< "\"\n";
return 0;
}


A string is in no way a vector<char> or any vector. It's a typedef for
std::basic_stri ng<char>.
Furthermore, your code invokes undefined behavior, because a string's memory
is not guarenteed to be contiguous.

- Pete

Jul 22 '05 #8
Dave Townsend wrote:

Julie,

If you make use of the fact that string is actually a vector, you can do the
following,
which follows somewhat your approach, but results in much simpler and few
lines of code,
and doesn't require the explicit inclusion of the vector template class.
Other than that, its exactly the same underlying idea you posted. <snip> string foo("the quick brown fox jumped over the lazy dog");
string bar(foo);

// modify the copy of the original string
char* c = &bar[0];
foobar(c);
Two problems that I'm aware of:
char* c = &bar[0];
/May/ be valid for c, but not c+1 as it isn't required that the underlying
character elements are stored contiguously.
foobar(c);


There is no guarantee that c is '\0' terminated, the standard doesn't require
that the underlying character array(s) are null terminated.

Comments?
Jul 22 '05 #9
Victor Bazarov wrote:
Alan Johnson wrote:
Victor Bazarov wrote:
- is 100% conformant(?)


As soon as the requirement for contiguousness of 'std::vector' storage
makes it into the Standard (if it hasn't already) and trickles down to
all library implementations (if they haven't done it already to begin
with).


Just to remove any uncertainty here, from Section 23.2.4/1 :

"The elements of a vector are stored contiguously, meaning that if v
is a vector<T, Allocator> where T is some type other than bool, then
it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size()."

I take it, that's from the newer edition of the Standard, correct?
Is that ISO/IEC 14882-2003?

V


Correct.

Alan
Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
13074
by: Victor Hannak | last post by:
I am taking a program written in Borland C++ Builder 4 and converting the non-GUI related code to be generic c++ that can run anywhere. My main issue at this point is dealing with the string classes used in this program. All strings in this program are of the Borland AnsiString class. I would like to convert them over to use std::string. ...
10
8157
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is effectively impossible to forward declare std::string. (Yes I am aware that some libraries have a string_fwd.h header, but this is not portable.) That...
16
16403
by: Khuong Dinh Pham | last post by:
I have the contents of an image of type std::string. How can I make a CxImage object with this type. The parameters to CxImage is: CxImage(byte* data, DWORD size) Thx in advance
8
4801
by: Jason Heyes | last post by:
If s is a std::string, does &s refer to the contiguous block of characters representing s?
1
5046
by: Wild Wind | last post by:
Hello, I have the following methods I've written to convert from String* to std::string and back: static void ConvertFromStdString(std::string& inStr, System:String* outStr) { outStr = new String(inStr.c_str()); }
15
6883
by: roberts.noah | last post by:
Are there any decent benchmarks of the difference between using c strings and std::string out there? Google isn't being friendly about it. Obviously this would be dependant on different implementations but I don't care. I would be happy to find ANY comparison at this point if it was valid and semi scientifically done.
2
10867
by: pookiebearbottom | last post by:
Just looking for opinion on which of the 3 methods below people use in their code when they convert a 'const char *' to a 'const std::string &' came across #3 in someone's code and I had to think for a sec. At first I read it as converting a 'const char *' to a 'std::string *' void f(const std::string &s) { std::cout << s.size() <<...
11
2886
by: Jacek Dziedzic | last post by:
Hi! I need a routine like: std::string nth_word(const std::string &s, unsigned int n) { // return n-th word from the string, n is 0-based // if 's' contains too few words, return "" // 'words' are any sequences of non-whitespace characters // leading, trailing and multiple whitespace characters // should be ignored.
8
13734
by: Edson Manoel | last post by:
I have some C++ unmanaged code that takes std::string& arguments (as reference), and fills them (possibly growing the string). I want to call this code through PInvoke (DllImport), possibly using wrapper layers in unmanaged C++ and C#. I've thought about two approaches: 1) To pass a StringBuilder, this is converted to a char* in C++,...
0
7847
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7778
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8148
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5342
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3781
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3798
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2292
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1389
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1113
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.