Serving the Quantitative Finance Community

 
User avatar
Mano

converting integer to char

October 29th, 2002, 1:42 pm

Is it possible to read and integer and convert it to a string to use say the third character in the string.Maybe there is a better way to do it.
 
User avatar
gc
Posts: 10
Joined: September 21st, 2002, 10:08 pm

converting integer to char

October 29th, 2002, 2:43 pm

Hi Mano,You don't specify which programming language you are using.<hr />If you are using C, the function sprintf() is your friend. Or even better, snprintf(). They are both prototyped in <stdio.h>For example:int number = 12345678;char number_in_string[100];sprintf( number_in_string, "%d", number);or even better:snprintf( number_in_string, sizeof(number_in_string), "%d", number);For some arcane reason Microsoft decided to rename snprintf() to _snprintf(), but it works in the same way. If you are compiling under Solaris, snprintf() is only available from SunOs 4.6.<hr />If you are using C++, you should use stringstreams.Stroustrup suggests the following function to convert from integers to STL-strings:string itos(int i) // convert int to string{ stringstream s; s << i; return s.str();}The code is copied from his homepage: http://www.research.att.com/~bs/bs_faq2 ... -string<hr />Of course, if you are coding in basic, the old good function "str$( <number> ) " will do as well, and you can then extract the desired character with either of mid$(), left$() or right$().I hope this helps.gc
 
User avatar
Mano

converting integer to char

October 29th, 2002, 3:10 pm

Thanks gc. Sorry I did not mention it, I was looking to do it in C++. So, you have answered my question perfectly.