Handling Strings

Some third-party libraries I use require byte arrays, some char arrays
some std::strings. Normally, when taking user defined input that is
suitable as a string, I use std::string, but find myself casting a lot
to make what I have work with various libraries. I use old-fashioned c-
style cast and it works for the most part, but I'm uncomfortable with
all the casting (it feels wrong).

So I wanted to ask others, how do you handle these situations when you
have libraries that want a certain character type (that could just as
easily be a string) and all you have is std::strings?

Thanks
0
byte8bits (134)
6/28/2010 3:11:32 PM
comp.lang.c++ 48813 articles. 0 followers. Post Follow

8 Replies
253 Views

Similar Articles

[PageSpeed] 44
Brad <byte8bits@gmail.com>, on 28/06/2010 08:11:32, wrote:

> Some third-party libraries I use require byte arrays, some char arrays
> some std::strings. Normally, when taking user defined input that is
> suitable as a string, I use std::string, but find myself casting a lot
> to make what I have work with various libraries. I use old-fashioned c-
> style cast and it works for the most part, but I'm uncomfortable with
> all the casting (it feels wrong).
>
> So I wanted to ask others, how do you handle these situations when you
> have libraries that want a certain character type (that could just as
> easily be a string) and all you have is std::strings?

For converting std::string to C-style strings you use c_str(), for the 
reverse operation you build std::string from C-style strings - I have no 
idea of what you mean with "byte arrays" since C++ has no "byte" type.

I don't see any need for casting, and about C style casts in particular, 
you can (you should) always replace them with the equivalent C++ 
explicit casts - if casting is really needed.

You could take advantage of posting some example and of mentioning the 
libraries you're using, if this answer didn't satisfy your question.

-- 
FSC
http://userscripts.org/scripts/show/59948
0
Francesco
6/28/2010 3:18:43 PM
On Jun 28, 11:18=A0am, "Francesco S. Carta" <entul...@gmail.com> wrote:

> For converting std::string to C-style strings you use c_str(), for the
> reverse operation you build std::string from C-style strings - I have no
> idea of what you mean with "byte arrays" since C++ has no "byte" type.

Yes, I use c_str(). Some libraries define byte (an unsigned char).

> I don't see any need for casting, and about C style casts in particular,
> you can (you should) always replace them with the equivalent C++
> explicit casts - if casting is really needed.
>
> You could take advantage of posting some example and of mentioning the
> libraries you're using, if this answer didn't satisfy your question.

Here is an example from Crypto++:

CryptoPP::Weak::MD4 hash;
byte digest[ 16 ];

// Here is one example where I cast to make the std::string I have
work
hash.Update((const byte*)generated_string.c_str(),
generated_string.length());
hash.Final( digest );

0
Brad
6/28/2010 4:47:53 PM
Brad <byte8bits@gmail.com>, on 28/06/2010 09:47:53, wrote:

> On Jun 28, 11:18 am, "Francesco S. Carta"<entul...@gmail.com>  wrote:
>
>> For converting std::string to C-style strings you use c_str(), for the
>> reverse operation you build std::string from C-style strings - I have no
>> idea of what you mean with "byte arrays" since C++ has no "byte" type.
>
> Yes, I use c_str(). Some libraries define byte (an unsigned char).
>
>> I don't see any need for casting, and about C style casts in particular,
>> you can (you should) always replace them with the equivalent C++
>> explicit casts - if casting is really needed.
>>
>> You could take advantage of posting some example and of mentioning the
>> libraries you're using, if this answer didn't satisfy your question.
>
> Here is an example from Crypto++:
>
> CryptoPP::Weak::MD4 hash;
> byte digest[ 16 ];
>
> // Here is one example where I cast to make the std::string I have
> work
> hash.Update((const byte*)generated_string.c_str(),
> generated_string.length());

I see, in such a case you really need the cast, and a static_cast should 
be fine.

I you don't like to scatter the casts over all of your code, consider 
making a function that takes a std::string and outputs the casted const 
byte* that you need.

Still, regular C-style strings need no casting, and I'm sure you'll take 
care that the cast is correct for any typedef of "byte" that you'll have 
to use - wrt passing the size() of the std::string.

-- 
FSC
http://userscripts.org/scripts/show/59948
0
Francesco
6/28/2010 5:03:19 PM

"Francesco S. Carta" <entuland@gmail.com> wrote in message 
news:4c28d5d6$0$6839$5fc30a8@news.tiscali.it...
> Brad <byte8bits@gmail.com>, on 28/06/2010 09:47:53, wrote:
>
>> On Jun 28, 11:18 am, "Francesco S. Carta"<entul...@gmail.com>  wrote:
>>
>>> For converting std::string to C-style strings you use c_str(), for the
>>> reverse operation you build std::string from C-style strings - I have no
>>> idea of what you mean with "byte arrays" since C++ has no "byte" type.
>>
>> Yes, I use c_str(). Some libraries define byte (an unsigned char).
>>
>>> I don't see any need for casting, and about C style casts in particular,
>>> you can (you should) always replace them with the equivalent C++
>>> explicit casts - if casting is really needed.
>>>
>>> You could take advantage of posting some example and of mentioning the
>>> libraries you're using, if this answer didn't satisfy your question.
>>
>> Here is an example from Crypto++:
>>
>> CryptoPP::Weak::MD4 hash;
>> byte digest[ 16 ];
>>
>> // Here is one example where I cast to make the std::string I have
>> work
>> hash.Update((const byte*)generated_string.c_str(),
>> generated_string.length());
>
> I see, in such a case you really need the cast, and a static_cast should 
> be fine.
>

static_cast is not fine, reinterpret_cast is.

/Leigh 

0
Leigh
6/28/2010 5:14:18 PM
Leigh Johnston <leigh@i42.co.uk>, on 28/06/2010 18:14:18, wrote:

> "Francesco S. Carta" <entuland@gmail.com> wrote in message
> news:4c28d5d6$0$6839$5fc30a8@news.tiscali.it...
>> Brad <byte8bits@gmail.com>, on 28/06/2010 09:47:53, wrote:
>>> hash.Update((const byte*)generated_string.c_str(),
>>> generated_string.length());
>>
>> I see, in such a case you really need the cast, and a static_cast
>> should be fine.
>>
>
> static_cast is not fine, reinterpret_cast is.

Whoops...

-- 
FSC
http://userscripts.org/scripts/show/59948
0
entuland (631)
6/28/2010 5:24:08 PM
On Jun 28, 11:47=A0am, Brad <byte8b...@gmail.com> wrote:
> On Jun 28, 11:18=A0am, "Francesco S. Carta" <entul...@gmail.com> wrote:
>
> > For converting std::string to C-style strings you use c_str(), for the
> > reverse operation you build std::string from C-style strings - I have n=
o
> > idea of what you mean with "byte arrays" since C++ has no "byte" type.
>
> Yes, I use c_str(). Some libraries define byte (an unsigned char).
>
> > I don't see any need for casting, and about C style casts in particular=
,
> > you can (you should) always replace them with the equivalent C++
> > explicit casts - if casting is really needed.
>
> > You could take advantage of posting some example and of mentioning the
> > libraries you're using, if this answer didn't satisfy your question.
>
> Here is an example from Crypto++:
>
> CryptoPP::Weak::MD4 hash;
> byte digest[ 16 ];
>
> // Here is one example where I cast to make the std::string I have
> work
> hash.Update((const byte*)generated_string.c_str(),
> generated_string.length());
> hash.Final( digest );

How about:

template<>
struct std::char_traits<byte>
{
    // define the typedefs and static methods as appropriate
};

typedef std::basic_string<byte> ByteString;
0
Sousuke
6/28/2010 5:49:01 PM
On 28 juuni, 20:49, Sousuke <s0s...@gmail.com> wrote:
> On Jun 28, 11:47=A0am, Brad <byte8b...@gmail.com> wrote:
>
>
>
> > On Jun 28, 11:18=A0am, "Francesco S. Carta" <entul...@gmail.com> wrote:
>
> > > For converting std::string to C-style strings you use c_str(), for th=
e
> > > reverse operation you build std::string from C-style strings - I have=
 no
> > > idea of what you mean with "byte arrays" since C++ has no "byte" type=
..
>
> > Yes, I use c_str(). Some libraries define byte (an unsigned char).
>
> > > I don't see any need for casting, and about C style casts in particul=
ar,
> > > you can (you should) always replace them with the equivalent C++
> > > explicit casts - if casting is really needed.
>
> > > You could take advantage of posting some example and of mentioning th=
e
> > > libraries you're using, if this answer didn't satisfy your question.
>
> > Here is an example from Crypto++:
>
> > CryptoPP::Weak::MD4 hash;
> > byte digest[ 16 ];
>
> > // Here is one example where I cast to make the std::string I have
> > work
> > hash.Update((const byte*)generated_string.c_str(),
> > generated_string.length());
> > hash.Final( digest );
>
> How about:
>
> template<>
> struct std::char_traits<byte>
> {
> =A0 =A0 // define the typedefs and static methods as appropriate
>
> };
>
> typedef std::basic_string<byte> ByteString;

When some library/framework/platform interface needs something as
input then best idea is provide that to it with conversion functions.
It is not so good idea to use the types of library in your internal
application data and logic.

Few years pass and you realize that you need to switch to different
library. Then it is hard because some "myte" of "cbangbang" library
has spread all over your code and now you depend on it. Whereas with
conversion/translation layers you may even support usage of multiple
competing libraries in parallel when need arises.
0
ISO
6/28/2010 9:10:56 PM
On Jun 28, 12:47=A0pm, Brad <byte8b...@gmail.com> wrote:
> Here is an example from Crypto++:
>
> CryptoPP::Weak::MD4 hash;
> byte digest[ 16 ];
>
> // Here is one example where I cast to make the std::string I have
> work
> hash.Update((const byte*)generated_string.c_str(),
> generated_string.length());
> hash.Final( digest );

In addition to what others have said, you might want to
provide a global operator<< so that you could write

  hash << generated_string;

Or something similar.

--Jonathan
0
Jonathan
6/28/2010 9:52:25 PM
Reply:
Similar Artilces:

DELETE & invalid handle object
Hello all, any body know why I was given two answers, "Invalid handle object" and "ans =..." I assume p is the same as a. Anybody knows why? >> global p >> if ~isempty(p) delete (p); else 'line not found'; end ??? Error using ==> delete Invalid handle object. >> global a >> if ~isempty(a) delete (a); else 'line not found' end ans = line not found It looks like "p" exists but is not a valid handle, and "a" does not exist. You might want to check out the "i...

Solaris 10: xlib drawing for text and string failing using xsun
Hi all, I have sparc system and Iam using xsun on solaris 10 and ps -ef | grep -i xsun gives this: /usr/openwin/bin/Xsun :0 +nkeyboard +nmouse -dev vfb -dev vfb screen 0 1028x102 Now I am trying to use XDrawString and XDrawText for simple one character drawing but to no avail as these calls don't generate anything. All line generation and bitmap are rendered correctly on the virtual frame buffer to generate a tiff file. The same set of calls are working great on sun 2.6. What can be the problem? I can't seem to find any solution to that? ////////////////////// These calls fail com...

Using uft8 encoded strings in windows filesystem
I've got a project which is completely enconded in UTF-8. The database and the served pages are in this encoding. But when using filesystem functions like mkdir() fopen(), etc. -UNDER WINDOWS- it produces wrong file and directory names. If I mkdir('=E6=97=A5=E6=9C=AC=E8=AA=9E') the directory =C3=A6=E2=80=94=C2= =A5=C3=A6=C5=93=C2=AC=C3=A8=C2=AA=C5=BE is created in the filesystem. This does not seem a filesystem limitation as if I create manually from the windows explorer a directory with the same name, the directory is created correctly. How can i write my utf filenames as they ...

RE: [tao-users] Request Handling in TAO #2
Here is the Problem Report Form TAO VERSION: 1.4a_p7 HOST MACHINE and OPERATING SYSTEM: Microsoft Windows 2000 5.00.2195 SP3 TARGET MACHINE and OPERATING SYSTEM, if different from HOST: Idem COMPILER NAME AND VERSION (AND PATCHLEVEL): Microsoft Visual VC++ 7.1.3088 CONTENTS OF $ACE_ROOT/ace/config.h /* -*- C++ -*- */ //============================================================================= /** * @file config-win32.h * * $Id: config-win32.h,v 1.1.1.5 2005/01/03 19:36:20 chad Exp $ * * @brief Microsoft Windows configuration file...

best efficient and readable way to concatenate strings (or the best trade-offs)
Since C++ (and STL) have many ways to do string concatenation, I want to hear (read) from you how you do to concatenate strings with other strings and other types. The approaches I know are: -- ostringstream this does the job well, but: * all types involved have to support operator<< * we will lose some readibility in the code because we will always have to create a temp object to do the concatenation int n; float x; .... ostringstream temp; temp << "we bought " << n << " items at " << x << " price"; notebook.add(temp.str()); ...

to handle keys
I would like to quit a dialog based application with the key "F9". But the function "OnKeyUp" doesn't respond to keys. How can i do that ? Thanks Nati On Fri, 13 Jan 2006 14:11:04 +0100, nati <nati31@free.fr> wrote: >I would like to quit a dialog based application with the key "F9". >But the function "OnKeyUp" doesn't respond to keys. >How can i do that ? OnChar or OnKeyDown Also depends if you're using MFC or straight Win32. Check the "Virtual Keycodes" docs as well. How are you checking th...

getting {string} from \${string}
Hi folks. Perl newbie here. Having a heck of a time with something which probably isn't that hard... When debugging code in progress, I often find myself typing: print "\$var1=$var1, \$var2=$var2 \n"; not a big deal, but when you do it all the time, it would be nice to save some typing by putting it in a subroutine, such as: dbg_pr($var1,$var2); Easy enough if I just wanted the values, but I want to print both the variable names and the values, and I'd like to get both from one string. If I pass $var1 or \$var1 I can get the value but not the variable name, and if I p...

String quarks
Hi, Xlib can convert strings to integers and back uniquely (quarks are the integers). What is a common algorithm for doing this? In article <d8ssg2-4j2.ln1@main.anatron.com.au>, Russell Shaw <rjshawN_o@s_pam.netspace.net.au> wrote: > Hi, > > Xlib can convert strings to integers and back uniquely (quarks are the > integers). > What is a common algorithm for doing this? Use a hash table and a counter. Look up the string in the hash table. If it's found, return the associated integer. If not, increment the counter and store it in the hash table keyed off...

Handling Array in Stateflow!?
Hi, I am using Simulink and Stateflow, and I have an array as an input into the stateflow. How do I manipulate the array within stateflow to trigger states or even to change the array itself? For example, if we have a 1 Row x 10 Column array, I'd like a trigger that says:- If any one column within that array = 0, go to this state. Is this possible? please help! Cheers, Alex Use for example: ml.any(vector) as a transistion to the state. The 'ml.' introduce a MATLAB command. Hope this was what you're searching for. Regards, Stefan Alex wrote: > > > Hi, > &g...

String handling
I'm trying to count the number of leading spaces in lines from a file using: tfc=0 w=$0 for(i=1;i<=NF;i++) if (w[i] == ' ') tfc++ else break} but this generates a syntax error What am I doing wrong ?? Any help ... Thank you Colin In article <33c7bd32.0504071709.5711f3e3@posting.google.com>, colinhay66@hotmail.com (Colin) wrote: > I'm trying to count the number of leading spaces in lines from a file using: > > tfc=0 > w=$0 > for(i=1;i<=NF;i++) if (w[i] == ' ') tfc++ else break} > > but this generates a syntax error > > ...

Access Split Database Data Handling
Just a query about how clever access is, I'm using access 97. When using a "split" database with a separate front-end and with the data file on a separate server on the network how does access handle the data; Does it transfer all the data across the network and process it locally on the front end or does it process it on the server the data file is held on? If I put my queries in the access data file on the server would this result in the queries being run on the server? Access is Client-Side, SQL Server is Server-Side. Access will bring all the information to your local co...

newbe: documentation string length
Consider (defun resize-array (array amount) ;; improved version thanks to Fred Gilham "Expands array by the specified amount and returns the possibly new array. Amount can be negative" (adjust-array array (+ (length array) amount))) This is all fine and good as: CL-USER 14 > (documentation 'resize-array 'function) "Expands array by the specified amount and returns the possibly new array. Amount can be negative" Except that, the line is too long *in the definition*. ie: it doesn't fit my self-imposed 80 characters per line limit. So, I'd rather...

Question on WM_PAINT handling
Hello I am trying to develop a time based charting application. Basically, application displays stock prices for a set time interval. So prices will be initially displayed on left and dots gradually added to the right until get to right edge of chart when prices on far left will be scrolled off to the left - if you see what I mean. I have got the chart dimensions sorted out but this static data (labels etc) is in a WM_PAINT handler. But it doesn't seem such an efficient way to do it - re-writing to the window every time. For this type of charting application, what is best ...

Error handling with exceptions
Hi there, I wrote a simple program that works in this way: - if the current copy is outdated, download an xml file (= schedule from now on) if (schedule.testUpdate() == false) { new Downloader().download(URL) } - parse it new Parser().parse() - show the parsed content System.out.println(getParsedContent()) I was wondering how to handle correctly the parsing errors in case that the schedule is not downloaded (because it is updated): try { //parsing } catch (Exception e) { // what to do here??? } I think that a solution is to download a new schedule and then parse it, but how can I do this? ...

Dynamic C String Question
I'm writing a program in C, and thus have to use C strings. The problem that I am having is I don't know how to reallocate the space for a C string outside the scope of that string. For example: int main(void) { char *string1; string1 = malloc(6); sprintf(string1, "Hello"); foo(string1); } void foo(char *string) { string = realloc(string, 12); strcat(string, " World"); } In this example, I reallocate the space for a string declacred in another function in the function foo. But, after it returns to main from the function foo, the C string will only contain &...

Session handling, login across all subdomains
I run a Joomla website and am familiar with php in some but not all aspects. Currently I am trying to find some solutions related to session handling. Am I correct in saying that "login" is kept in sessions? I can see active sessions in my mysql database, but is that the only place this information is stored? Sessions and cookies I know are related also, but how specifically (session info stored in cookies?)? Right now, when users login at example.com, and then visit subdomain.example.com, they are not logged in at the subdomain. I am trying to change this so that users logged in o...

Delete apostrophes from a string
Hello, how can I delete all apostrophes from the string? e.g. string = ss' s45' I tried the following commands, but they didn't solve the problem: newstring = regexprep(string,char(39),''); newstring = strrep(string, char(39), ''); Thanks. "Liana" wrote in message <j78hl4$h8c$1@newscl01ah.mathworks.com>... > Hello, > > how can I delete all apostrophes from the string? e.g. > string = ss' s45' > > I tried the following commands, but they didn't solve the problem: > newstring = regexprep(string,char(39),...

Javascript: How to convert userinput *string* to *regex* for use in replace
I wonder how one converts a string into a real regex... if I try something like: var sRegex=userinput.value var sResult = sSomestring.replace(sRegex, "xxx"); the sRegex is interpreted as a string and not as a real /regex/ How can I change this so the user can enter a regex and have it interpreted? I guess this requires some kind of cast but to what kind of objectype? On 14 Aug 2003 08:11:32 -0700, paulgiverny@hotmail.com (Phil) wrote: >I wonder how one converts a string into a real regex... > >if I try something like: > >var sRegex=userinput.value >var sResul...

[wxMac] new capture handling
Hi =20 following the bug report of Riccardo I have fixed the 'out of toplevel window' situations for capture. But I'm not sure whether I have not introduced new problems, so in line toplevel.cpp : 1730 you can turn off the NEW_CAPTURE_HANDLING by setting it to 0 Thanks for your feedback in advance, Stefan --------------------------------------------------------------------- To unsubscribe, e-mail: wx-users-unsubscribe@lists.wxwidgets.org For additional commands, e-mail: wx-users-help@lists.wxwidgets.org On 25/07/05, Stefan Csomor <csomor@advancedconcepts.ch...

strtotime() not able to handle 04/29 correctly???
Hi, I calculate the amount of days between two dates like this: $start = strtotime($_SESSION['sdate']); $end = strtotime($_SESSION['hdate']); echo ($end - $start); $duration = ($end - $start) / 3600 /24; $duration+=1; //plus one day echo " The ad will show for ".$duration." day(s)<br/>"; Which generally works fine but things seem to mess up when I have a start sdate of 2012-02-29 and an hdate of 2012-04-01. I get a duration of: 32.9583333333 Why is this? That's messing up my calculations. Is there a better way to do this? Than...

Re: Strings to Integers
On 7/1/06 at 5:11 AM, vs@it.uu.se (Virgil Stokes) wrote: >The following is an example of a list that contains times in >min:sec, >{12.33, 120:03, 343:59, 1:00} >where each element is of String type. >Is there a "smart" way to convert lists such as this into Integer >type for both minutes and seconds? I am going to assume there is a typo in you list above and the first item should be 12:33. If I have this correct, then the following will do what you want. In[1]:= t={"12:33","120:03","343:59","1:00"}; Map[T...

handles and GUIDE
Hii guys, I'm trying to learn more about handles in MATLAB because I'm creating a graphic interface using GUIDE and its essential to know how to use handles. I have a lot of situations where I need to use a value that is provided by a previous function, for example: My first pushbottom provide an value to an editable text object, when you write the number 2 in this place, I have a variable called number that assigns this value; In another part of my program, I am using a list of option object and when I select the first item of my list I want to my program print that numb...

problems with Close(handle) ?
Hello everyone ! I just wanted to know what i need to tinker with - if on my Linux installation, when i run Close(h), i get an error: >>h=figure; >> close(h) ??? Attempt to execute SCRIPT persistent as a function. Error in ==> close>request_close at 126 persistent in_request_close; Error in ==> close at 118 status = request_close(h); >> close(gcf) ??? Attempt to execute SCRIPT persistent as a function. Error in ==> close>request_close at 126 persistent in_request_close; Error in ==> close at 118 status = request_close(h); >> close all ...

Asynchat and error handling
Hello, I'm trying to add some better error handling to an async_chat client. What I want is to retry or terminate gracefully if the connection to the server doesn't succeed. Here's what I have: import asyncore, asynchat, socket class http_client(asynchat.async_chat): def __init__(self, host): asynchat.async_chat.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) terminator = '\x00\xDE\xED\xBE\xEF\x00' self.buffer = 'I can haz data?' + terminator self._connected = False self.set_terminator(ter...

Re: Entering a binary string
> -----Original Message----- > From: Pete [mailto:Nospam@blank.com] > Posted At: 07 September 2004 05:45 > Posted To: c > Conversation: Entering a binary string > Subject: Entering a binary string > > > Sorry for the ambiguity of my last post, What I am try to do > is enter a 10 > bit binary string > eg: 1110001010 and then permute them into an array using an > array containing > 3,5,2,7,4,10,1,9,8,6 as the index, so the 1st bit will be in > the P10_out[3], > 2nd bit in P10_out[5] and so on. .... > for(i=0; i<10; i++) { > index ...