Message-ID: <36FE8749.6CC4C5AC@jps.net> Date: Sun, 28 Mar 1999 11:47:21 -0800 From: Dennis Yelle X-Mailer: Mozilla 4.51 [en] (Win95; U) X-Accept-Language: en MIME-Version: 1.0 Newsgroups: comp.os.msdos.djgpp Subject: Re: Converting between varable types References: <7dlh6c$4b3$1 AT nnrp1 DOT dejanews DOT com> Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit NNTP-Posting-Host: 209.239.193.110 X-NNTP-Posting-Host: 209.239.193.110 X-Trace: 28 Mar 1999 20:08:51 -0800, 209.239.193.110 Lines: 70 X-NNTP-Posting-Host: 209.63.224.240 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com ryan_brown AT my-dejanews DOT com wrote: > > How do you convert data between variables of different types? I need to > convert the data in a float variable to a char variable. In pascal you could > just use funcitons like FloatToStr() however in c I can't find anything. I > have heard of casting but I can't get it to work and there isn't any > information on it anywhere on the internet as far as I can tell. Could > someone point me to some source code or a function that I could use for > converting this stuff? thanks in advance. There are lots of ways to do it, but no one way is best in all cases. Here is one way: ---------------------------- cut here ------------------------------ /* The code below was written by Dennis Yelle on March 28, 1999. Use it any way you like. */ #include #include #include char *d2s( double d) { char *out; static char buf[400]; /* 400 is probably big enough */ sprintf( buf, "%g", d); /* you might want to try %f instead of %g here */ out = strdup( buf); if ( ! out ) { fprintf( stderr, "Sorry, not enough memory.\n"); exit(9); } return out; } int main( int argc, char **argv) { double d; float f; int i; char *p; if ( argc < 2 ) { d = 9; for( i=0; i<310; i++) { d *= 10; p = d2s( d); printf( "i = %d, d = %s, ", i, p); free(p); f = d; p = d2s( f); printf( "f = %s\n", p); free(p); } } else { for( i=1; i