Problem converting integers to string

Dear Rooters

Why does the following code not work?

{
 char  buffer[20]="25";
 char* ptr=buffer;
 int   byte; 

 printf ("\r\n Eingabe: %s ", buffer);
 byte =atoi(buffer); 
 printf ("Zahl: %.2Xh ", byte);
 ptr =itoa(byte, buffer, 10);
 printf ("Byte als String: %s \r\n", ptr);
}

results in the following CINT output:
Error: Function itoa(byte,buffer,10) is not defined in current scope (tmpfile):8:
*** Interpreter error recovered ***
root [1] .q
Eingabe: 25 Zahl: 19h

Compilation on MacOS X 10.4.4 results in the following error:
error: ‘itoa’ was not declared in this scope
although I have included "#include ".

My current solution is:

Int_t idx = 25;
TSting str = ""; str += idx;

Thank you in advance.

Best regards
Christian

Why don’t you use the Form() method to convert integer to string ?
Form("%d",i);

Hi,
itoa is not part of ANSI-C, and so some compilers don’t offer it.
Cheers, Axel.

Thank you for this hint. I did not know that I can use Form().
It is sad that ANSI-C (or C++) has no possibility to convert numbers to string.

Best regards
Christian

Hi Christian,

ISO C++ avoids char* where possible; you’d instead use a stringstream and operator<<(). In C, you’d use sprintf((char*)buf, “%f”, (float)f); But as Olivier pointed out, Form hides the buffer management from you and is thus easier to use.

Cheers, Axel.

Dear Axel

Thank you for this explanation. What I was hoping was that I could simply write:
TString str = TString(25);
but this is not possible, I have to use:
TString str = “”; str += 25;
or use Form().

Best regards
Christian

[quote]Dear Axel

Thank you for this explanation. What I was hoping was that I could simply write:
TString str = TString(25);
but this is not possible, I have to use:
Christian[/quote]

:slight_smile: That’s possible, but the semantic of such a ctor is different:

//from TString.h:

TString(Ssiz_t ic); // Suggested capacity

Dear Axel

Maybe, I am too stupid to understand what you mean, because my first trial was:

root [0] TString s =TString(25)
root [1] s
(class TString)""
root [2] Int_t i = 12
root [3] TString t =TString(i) 
root [4] t
(class TString)""

Or do you mean that it could be possible but is not implemented?

Best regards
Christian

I mean this ctor can pre-allocate some memory for your string (Ssiz_t ic) :slight_smile: It doesn’t create string representation for ic :slight_smile:

For example, you can do with this ctor:
//
TString string(bigNumber);

for(int i = 0; i < anotherBigNumber; ++i)
string += something;
//
and avoid memory reallocations.

Hi,

Thank you, now I understand.

Best regards
Christian