473,785 Members | 2,736 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
24 11037
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;


So then, under the presumption that this is about as 'clean' as it can get,
does anyone have a comment on why a method for direct access wasn't provided in
the std::string implementation? I'd have presumed that something like that
would have been requisite to be more compatible w/ C and C-style strings and
interfaces.

Something like:

class string
{
private:
char * _accessbuf; // NULL initialized in constructor
public:

char * string::access( const size_t num_chars)
{
delete [] _accessbuf;
_accessbuf = new char[num_chars+1];
copy(_accessbuf , num_chars, 0);
_accessbuf[num_chars] = '\0';
return _accessbuf;
}

void string::commit( const bool commit=true)
{
if (_accessbuf)
{
if (commit)
{
*this = _accessbuf;
}
delete [] _accessbuf;
_accessbuf = NULL;
}
}
// etc.
};

Then, accessing C-style interfaces would resolve to:

GetFileName(str .access(_MAX_PA TH), _MAX_PATH);
str.commit();

instead of the cumbersome method in my original post.

Comments?

(Note: the names access and commit are completely arbitrary, more appropriate
names probably exist.)
Jul 22 '05 #21
Julie wrote:
Julie wrote:

I'm re-evaluating the way that I convert from a std::string to char *.


Maybe I misunderstood your post, by I find string::c_str() works well for
me.

--
Chris Gordon-Smith
London
Homepage: http://graffiti.virgin.net/c.gordon-smith/
Email Address: Please see my Home Page
Jul 22 '05 #22
Chris Gordon-Smith wrote:

Julie wrote:
Julie wrote:

I'm re-evaluating the way that I convert from a std::string to char *.


Maybe I misunderstood your post, by I find string::c_str() works well for
me.


c_str() returns a const pointer, so you can't directly modify the contents.

My proposal is for something that would encapsulate my original code into two
methods that would return a non-const pointer so that the contents can be
directly modified.
Jul 22 '05 #23
On Sat, 26 Jun 2004 09:25:59 -0700, Julie wrote:
Chris Gordon-Smith wrote:
Julie wrote:
Julie wrote:

I'm re-evaluating the way that I convert from a std::string to char *.


Maybe I misunderstood your post, by I find string::c_str() works well for
me.


c_str() returns a const pointer, so you can't directly modify the contents.

My proposal is for something that would encapsulate my original code into two
methods that would return a non-const pointer so that the contents can be
directly modified.


Why, exactly, do you want to do this?

--
Some say the Wired doesn't have political borders like the real world,
but there are far too many nonsense-spouting anarchists or idiots who
think that pranks are a revolution.

Jul 22 '05 #24
Owen Jacobson wrote:

On Sat, 26 Jun 2004 09:25:59 -0700, Julie wrote:
Chris Gordon-Smith wrote:
Julie wrote:
Julie wrote:
>
> I'm re-evaluating the way that I convert from a std::string to char *.

Maybe I misunderstood your post, by I find string::c_str() works well for
me.
c_str() returns a const pointer, so you can't directly modify the contents.

My proposal is for something that would encapsulate my original code into two
methods that would return a non-const pointer so that the contents can be
directly modified.


Why, exactly, do you want to do this?


From my previous post:
... to be more compatible w/ C and C-style strings and interfaces.

Jul 22 '05 #25

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

Similar topics

13
13096
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. In order to keep from breaking the original program, I was hoping to use std::string everywhere...
10
8184
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 said, is there any real reason why I can't derive an otherwise empty
16
16429
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
4817
by: Jason Heyes | last post by:
If s is a std::string, does &s refer to the contiguous block of characters representing s?
1
5061
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
6905
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
10937
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() << "\n";
11
2903
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
13765
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++, the wrapper code converts the char* to a std::string (copy), and in the
0
9480
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10319
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10087
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8971
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7496
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6737
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5380
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2877
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.