Handling Strings

  • Permalink
  • submit to reddit
  • Email
  • Follow


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
Reply byte8bits (134) 6/28/2010 3:11:32 PM

See related articles to this posting


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
Reply 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
Reply 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
Reply 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
Reply 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
Reply 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
Reply 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
Reply 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
Reply Jonathan 6/28/2010 9:52:25 PM
comp.lang.c++ 48349 articles. 29 followers. Post

8 Replies
200 Views

Similar Articles

[PageSpeed] 16


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

string A = string A + string B (adding strings)
Hi, how can I perform the operation of adding string to string. string_A = string_A + string_B In particular I have to do: handles.hsl_current_string{1}(hsl_current_value{1}, :) = [handles.hsl_current_string{1}(hsl_current_value{1}, :), ' ' z1_value, ' ' z2_value, ' ' z_value] where: string_A = handles.hsl_current_string{1}(hsl_current_value{1}, :) string_B = ' ' z1_value, ' ' z2_value, ' ' z_value I am dealing with GUI, string_A is the value of the listbox, and string_B is the value I would like to add to the string_B and rep...

Strings, Strings and Damned Strings
I have an int variable (always <100) that I want to convert to a two character string, e.g. if myint = 1, mystr = "01" if myint = 81, mystr = "81" At the moment I can't figure out how to do this cleanly. Then I wish to push a bunch of these strings into an array, for example: typedef char LABEL[3]; LABEL mystrArray[100]; But having read a couple of tutorials I am still no clearer on the best way to do an "array of strings" in this situation, nor how to do it. Any help much appreciated! cheers, Ben Ben wrote: > I have an int variable (always &...

Strings, STRINGS, and crazy strings!
Oh my head... Someone, please bail this choking programmer out of a fix. Here's what I got. 1. A multi-line Textbox control. 2. Enter 3 lines of text (each line separated by hitting the Enter key). 3. In my routine, I transfer the Textbox.text into a string variable, say sString. 4. Then I parse this string with my Parsestring routine that places each individual string into an array called sWords() and the string count into lCount. 5. Next is a For/Next loop to print each string found in sWords() at the same starting point on my Picturebox control (the textbox is in this conta...

string.fine(string+string...
Hi after reading the docs, I was hoping this would work, but I can't find out why. string a = "I "; string b = "am"; int ego; if(sentence.find((a+b).c_str(),0)!= string::npos) ego++; from the docs **************** size_type find( const string& str, size_type index ); size_type find( const char* str, size_type index ); size_type find( const char* str, size_type index, size_type length ); size_type find( char ch, size_type index ); thanks Gary Wessle <phddas@yahoo.com> writes: > Hi > > after reading the docs, I was hoping this would work, ...

String[] to String
/* I am writing this class to see the output of:args.toString();I want to see if the toString() method on the String[] will convertthe array contents into one string or it will write out it's typename,i.e. the <code>Class</code> class' name.As observed, the output is[java.lang.String@1693e2;which looks like the array's underlying type's name and the startingmemory address.*/public class Ats /*implying Array To String */{ public static void main(String[] args) { if ( args.length == 0 ) System.out.println("Usage: ats arg1 [arg2 [arg3...]]"); else Syste...

when string is not a string
Curious javascript sample. Consider the following code: var s = "asd" var f = function() { return typeof(this) } An expression typeof(s) returns true (as it is expected), but f.call(s) returns false! To make matters worse consider the following snippet: var s = "asd" var f = function() { return this instanceof String } An expression f.call(s) returns true, but (s instanceof String) returns false! The question is why call transforms this to an object? Is it made for unification, e.g. to make this iterable using 'for (var i in this)' loop?...

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 > > ...

String or string
I am doing something where I do=20 If "force" || "spells" Puts "blah" When I use it it gives a warning about comparing strings, what's happening a= nd how do I fix it? Scratch.mit.edu. Go there! -gbear605= It doesn't seem to mind if those are pre-assigned ... ruby-1.9.2-p0 > if "force" || "spells" ruby-1.9.2-p0 ?> puts "blah" ruby-1.9.2-p0 ?> end (irb):3: warning: string literal in condition (irb):3: warning: string literal in condition blah => nil ruby-1.9.2-p0 > f = "forc...

string of strings...
I got an array of id's : ids = [22443, 22468, 22371, 22218, 22472, 22377, 22245] I would like to get a string of strings (to be used in SQL WHERE..IN clause " '22443' , ' 22468' , ' 22371' , ' 22218' , '22472' , '22377' , '22245' " If a use ids.join(','), I get "22443,22468,22371,22218,22472,22377,22245" which is obviously not useful for SQL.... is there any shorcuts or should I concatenate each element ? thanks joss On 12/19/06, Josselin <josselin@wanadoo.fr> wrote: > I got an array...

string + string
Hi any idea why I am getting something like main.cpp:177: error: invalid operands of types ‘const char [11]’ and ‘const char [8]’ to binary ‘operator+’ when trying to compile something like int main(int argc, char* argv[]) { string a = ".........." + "......."; cout << a << endl; } how can I solve this, I have few lines and use + to concatenate them together. thanks Gary Wessle wrote: > Hi > > any idea why I am getting something like > > > main.cpp:177: error: invalid operands of types 'const char [11]' and 'const ch...

string handling
I am a new Matlab programmer with lots of other programming experience. For the most part I love Matlab, but the string handling is terrible. Maybe someone with more experience can help me out. I have text file of data that I am trying to upload. It has fixed-length fields. Some fields are numeric, others are strings. The tricky thing is that each record in the text file is four lines long. I can run a four step loop so that I know which line I've got. I'm using strread to parse out the fixed-length fields out of each line. However strread ignors whitespace, which is variable in my ...

string handle problem
Hi, I encountered a string handle problem and need help. In my code, I have a string which value could be "a1/a2" or "a2/a3/a4" or "a2/b3/c3/a5", now I hope to get the last sub_string after "/", for "a1/a2", I need "a2", for "a2/a3/a4" , I need "a4", and for "a2/b3/c3/a5", I need a5. I knew I can use split command and then handle the list to get the last one, but it seems a little complex, Is there an easy way to get it? I'm thinking to use regexp, but regexp handle string in order from left to rig...

Documentation string handling
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I stumbled upon this as I played with the SLIME inspector: some objects supplied documentation with them, some didn't and now I'm trying to understand the different handling of documentation along the types of things one can define -- that would be structures, CLOS classes and (generic) functions. (Eventually this whole thing may be implementation dependent (SBCL here) but that would be an anwser, too.) I was in every case expecting to get the supplied string in some way. Now, just to reason about what I thought was happening in the ...

Cumbersome string handling...
Dear experts, a long time ago I spent a lot of time writing a useful program on linux/g++ with the String.h package (maybe somebody remembers this class String). Now, I am trying to reactivate this, but cannot compile it anywhere anymore, since the library is obsolete for a long time and has been removed from current g++ distributions. I've started implementing everything with the string class present in the ansi c++ standard library, but I am getting more and more the impression that I have to keep reinventing the wheel. There are no automatic conversions integer->string available ...

String handling #2
Hi! I use the Instrument Control Toolbox. I receive a string that is formated like this: "%d,%d," How can I separte the two float values? Thanks for help! Jonas In article <1178898234.277277.171420@u30g2000hsc.googlegroups.com>, Tschouns <tschouns@gmx.ch> wrote: >I use the Instrument Control Toolbox. I receive a string that is >formated like this: "%d,%d," >How can I separte the two float values? I'm not clear on what you are asking: %d would indicate an integer value, not a float. Anyhow, you can use textread() with a 'delimiter' par...

Handling Binary Strings
I am trying to handle binary strings in php. I get a binary output initialization vector from mcrypt as such: from mcrypt: $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); This output may have padded nulls at the end which are significant. I would like to convert all characters including all padding nulls at end and convert it in a string to be saved into a database in such a way that I can reconstruct it back to binary again later. base64_encode and decode is not doing the job. They don't seem to preserve the original binary value after base64_decode(). Can someone suggest so...

having trouble with string handling
I am trying to get the user to input the name of the .csv file they want to check if it exist and also the name of the text file they want to store the error if file is not exist. The following is the full source. I found that every time it generate a .csv file for the error log, instead of a txt file. What's wrong? #include <stdio.h> #include <time.h> #include <string.h> int main() { int e = 1; FILE *fp; char in[9]; //stores the file name for checking char out[21]; //stores the file name for output in case file is not found char AMH[] = "S...

String Handling #2
When we use scanf to enter a string in a charecter array then we do not use & sign before the string name because the name of the string points to the address of the first charecter of the string. Vijay wrote: > When we use scanf to enter a string in a charecter array then we do not > use & sign before the string name because the name of the string points > to the address of the first charecter of the string. Specifically the name of an array resolves to a constant pointer to the start of the array. So, if you pass an array of characters to scanf(), passing the array name i...

converting string to handle
I'm trying to turn several static text boxes to visible during a for loop routine. All of the text box tags are numerically chronilogical (textbox1, textbox2 etc.). So in my for loop I create a string 'handle.textbox_' and try to use the set command to turn the boxes to visible. My code is as follows: for i=1:1:(layers-1) texttag='text'; texttag=str2func(['handles.',texttag,num2str(i)]); set(texttag,'Visible','On') end and the error I receive is: ??? Error using ==> set Conversion to double from function_handle is not p...

string handling library
Does anyone know if there is any documentation available for the functionality in Str.h ? Thanks c-library.chm in the \bin directory "Caesar Romano" <Spam@uce.gov> wrote in message news:q682g4h2c1i8ek0cis7fj4el6sktm1rki1@4ax.com... > Does anyone know if there is any documentation available for the > functionality in Str.h ? > > Thanks "gedumer1" <gedumer1@bellsouth.net> writes: > c-library.chm in the \bin directory Much easier Help->Strings Regards Friedrich -- Please remove just-for-news- to reply via e-mail. On Fri, 24 Oct 2008 ...

Handling delimited strings
What would be the best programming languages for doing the following on *nix and/or M$? I'd like a command that can be peformed/executed/run (ASAP) with the following parameters: ACTION : Input : One of COUNT, LOCATE, INSERT, DELETE, REPLACE, EXTRACT STRING : Input : Any variable length type-less string. FILENAME : The full path name of a flat ASCII text file POSITION : A reference, or pointer, to a sub-string in FILENAME ORDER : Ascending or Descending (only relevant for LOCATE) JUSTIFICATION : Right or Left (only relevant for LOCATE) RETURN_VALUE : Output : Only applicable to COU...

construct handles from strings
Hi all, I need to generate handle from strings the handles are obtained in a separate function h.Edit.XDI = findob('Tag','Edit_XDI'); .... etc and are then passed to another function ThrLetCod(1,:) = 'XDI' ThrLetCod(2,:) = 'YDI' .... for i =1:40 .... HandleStr = ['h.Edit' ThrLetCod(i,:)]; ThrLetCodStr = get(HandleStr,'string') .... & checking the string ThrLetCodStr .... end this doesn't work. Why? -Pjotr > h.Edit.XDI = findob('Tag','Edit_XDI'); > ... >...

handles pass strings
Do "handles" pass strings? I have a program that enters a string using a popup box and passes it using handles to a input callback then an Evaluation callback. The proces worked for a number. In the Evaluation callback there is an error: if alpha = 'A' then delta = -delta; end; The error is in the equals statement in "if alpha = 'A' then". Does this mean that "handles" is not passing strings thru alpha to the Evaluation callback? i would say rather try strcmp(alpha,'A') ---> strcmp is case sensitive strcmpi(alpha,'A')...

Is this a bug? string handling
Found it in my autotest code, it's so strange. I'm thinking if that's a real bug? [root@pc1 ~]# expect expect1.1> set a "abdent/concentrator" abdent/concentrator expect1.2> set b "concentrator" concentrator expect1.3> set c [string trimright $a "/$b"] abd ####why is it not "abdent"??? expect1.4> set d "abdent1/concentrator" abdent1/concentrator expect1.5> set e [string trimright $d "/$b"] abdent1 ####this time ...