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++ 48373 articles. 29 followers. Post

8 Replies
206 Views

Similar Articles

[PageSpeed] 52


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

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

GUI handle from a string
heres the problem, i have a number of handles handles.ch_0_input to handles.ch_15_input what i want to do is to change the value of each handle in a for loop, instead of writing 16 lines of code and making it tidier i.e for n=1:1:16 ch_handle=['handles.ch_' num2str(n-1) '_input'] set(ch_handle,'Value',inputs(n,1)); end however i get the error "set Value must be a handle.", so is there any way to change the string to an handle i can use in the set command? or another way of doing it? Cheers Mike Mike wrote: > for n=1:1:16 > > ch_handle=['handl...

String handling in java
hello all, Recently,i got to know about an article on a site explaining about string handling in java.i found it very interesting and thought to share it with u all. http://www.ezdia.com/String-Handling-in-Java/Content.do?id=578 Peter victor wrote: > Recently,i [sic] got to know about an article on a site explaining about > string handling in java [sic].i [sic] found it very interesting and thought to > share it with u [sic] all. > httq://www.ezdia.scam/String-Handling-in-Java/Content.do?id=578 Spam is bad enough, but this disingenuous "I found a site" garbage is just ...

a question about handling strings
Hi everyone, I want to find a character * in a string and introduce a '/' character before that. I can get the character index of * using strfind. But I don't know the best way to introduce the character '/'? Does anybody know of a function that can allow me to obtain either the left n characters of a string or the right m characters. Regards, Ana Ana Alvarez wrote: > > > Hi everyone, > > I want to find a character * in a string and introduce a '/' > character before that. > > I can get the character index of * using strfind. But I don&#...

String handling and the percent operator
I have some code to autogenerate some boilerplate code so that I don't need to do the tedious setup stuff when I want to create a new module. So, my script prompts the user for the module name, then opens two files and those files each get the contents of one of these functions: def GetPyContents(module): boilerplate = \ """ class %s: pass if __name__ == '__main__': import unittest unittest.main('%s_t') """ return boilerplate % ((module,) * 2) def GetTestContents(module): boilerplate = \ """from %s import * import u...

Function handles versus strings
I'm writing an optimization routine which accepts a the name of a matlab function to be minimized and uses feval to evaluate that function. My question is, is there a major benefit to using function handles over strings in the input of feval? In general is it better to use function handles than just passing the name of the function as a string to feval? Thanks, Richard In article <hmo27k$lgt$1@fred.mathworks.com>, r.crozier@ed.ac.uk says... > > I'm writing an optimization routine which accepts a the name of a matlab function to be minimized and uses feval to eva...

string handling, file reading
hello, i have such a code. i want to create a vector of strings, read values and read files regarding to the filenames. thank you. testlist = {'test1' ; 'test2' ; 'test3'} for i=1:3 testcode = testlist(i) filename=horzcat(testcode,'_measurements.txt') data=dlmread(filename,'\t'); ... ... end "ben harper" <controlusc@gmail.com> wrote in message <i9r9o3$7s5$1@fred.mathworks.com>... > hello, i have such a code. i want to create a vector of strings, read values and read files regarding to the filen...

How does Fortran 90 handle strings?
Hi, I have this question in mind for quite a while. Suppose we have a string, declared 100 characters long. character(len=100)::string When I assign it a value or write to it like string="hello,world" write(string,fmt='(A)') "hello,world" What does Fortran do to all the elements of this string? Will it force the rest part of the string(after "hello,world") to be white spaces or any kind of special character or just leave it untouched. I ask this because I am in concern that could several assignments to the same string possibly to make the string in a chao...

How to handle weird strings with backslashes
Greetings, I need to process strings like ddXaXD@@K@@LB\b@wHPJB\c@{HPJBHc@pH`NB|b@ This string has \ and { so I can't do: set str {ddXaXD@@K@@LB\b@wHPJB\c@{HPJBHc@pH`NB|b@} cuz that will complain about having an extra { If I do set str "ddXaXD@@K@@LB\b@wHPJB\c@{HPJBHc@pH`NB|b@" The backslashes disappear. The backslashes in the above string do have meaning, and actually what I would like to do is change them to \\ so then I can process with the Tcl command: binary scan $str c* list which converts all characters, backslashes included into their ASCI...

How to use strings for error handling
Hi all, I want to push some errors on an error stack in my function. The first parameter of the push function is the name of the function where the error occured. For example: int MyFunction() { ... if(error1) pushError("MyFunction","Something is wrong"); ... if(error2) pushError("MyFunction","Something else is wrong"); ... if(error3) pushError("MyFunction","Something more is wrong"); } To make things easier and less cluttered I could define two macros: #define FUNCNAME(a) static const char funcname[]=#a; #define ...