quick C question.. outputting int as char

dowxp

Diamond Member
Dec 25, 2000
4,568
0
76
its been a while since C and i can't remember how to output say A+B in a string ( return type const char* )

say

foo ( a,b ) returns a integer\double. how do i output as a const char* ?

return (char*) foo(a,b)

obviously does not work. thanks in advance.

dowxp
 

dowxp

Diamond Member
Dec 25, 2000
4,568
0
76
sorry. forgot it existed. actually never thought about it. its either gen hardware or off-topic for me.
 

agnitrate

Diamond Member
Jul 2, 2001
3,761
1
0
Assuming it's the correct value for the character you want to display, just cast it when you output it.

printf("Your character is %c", foo(a,b) ); or something like that.

-silver
 

dowxp

Diamond Member
Dec 25, 2000
4,568
0
76
this is a class, i am not writing user interface. i merely have to return a const char* so that when the user cout's the function it works. btw, its really C++, i dont know why i put C in the topic
 

GermyBoy

Banned
Jun 5, 2001
3,524
0
0
<FONT face="Courier New">Sizes are different, so you can't "convert" per say. There are a few ways to do it, this I googled. I don't feel like writing code now.

int n = 500;
char x = (char)n; // gets the low byte
char y = ((n & 0xff00) >> 8); //gets the second lowest byte.</FONT>
 

GermyBoy

Banned
Jun 5, 2001
3,524
0
0
Originally posted by: notfred
shouldn't you be able to do this with printf?

If he was outputting to the screen then yes. It's very easy that way. However, he misinformed us, and would rather return it.

It's never too late to go to google and search.
 

PrincessGuard

Golden Member
Feb 5, 2001
1,435
0
0
You have to dynamically allocate a char array (or other object that can hold a string).

Then you can use sprintf() or an sstream to convert the number to a string and return it.

However, I'm not sure why you have to do this since cout can output ints and floats already.
 

manly

Lifer
Jan 25, 2000
13,356
4,112
136
You could use sprintf, but I can't remember the rules for memory deallocation of the returned buffer. I suppose the caller could free it, but that's why C is notorious for memory leaks.
 

Cat

Golden Member
Oct 10, 1999
1,059
0
0
int foo( int a, int b) {


}


char *foo_string( int a, int b ) {
char*buffer = new char[100];
int radix = 10; // base 10
itoa( a+b, buffer, radix );


return buffer; // calling function must free
}

char *foo_string2( int a, int b, char *buffer ) {

// assumes buffer holds enough chars
int radix = 10; // base 10
itoa( a+b, buffer, radix );


return buffer;
}