problems using pow() in sprintf()

Started by
3 comments, last by raptorstrike 19 years, 3 months ago
ok i have the following lines (well at least thats all you have to worry about) and for some reason this inserts a 0 after the | not pow(temp_left,temp_right) here it is: char Temp_Char[50]; sprintf(Temp_Char, "%d\0", pow(temp_left,temp_right)); reader.insert(reader.find("|",0)+1,Temp_Char); couple other things you migh want to know, temp_left ^ temp_right = 4 reader is a valid string, and i have include the math.h thanks for the help[smile]
____________________________"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie
Advertisement
What is the \0 for?

pow returns a float, not an int. Don't use %d.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
thats alot the problem was the \0 i dont know what it was doing i dont know much about sprintf but i changed the "%d" to "%f" and now i get the right answer (4) but i also get six zeros after that. Is there a way to trim the zeros?
____________________________"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie
Quote:Original post by raptorstrike
thats alot the problem was the \0 i dont know what it was doing i dont know much about sprintf but i changed the "%d" to "%f" and now i get the right answer (4) but i also get six zeros after that. Is there a way to trim the zeros?


No, the \0 was simply redundant, as "%d" already is {'%', 'd', '\0'}. The problem really was that you used %d instead of %f, so printf expected an int and not a float. Variadic functions do not do type conversions, so it just took the bits of the 4.0 float value and reinterpreted them as an int

And, yes, there is a way to trim the zeros, but no, I am not going to tell you here, because you'll be much, much better served by reading the printf format string documentation and by figuring out the logic of it yourself.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
thanks as always frunny [smile] ill read up on it
____________________________"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie

This topic is closed to new replies.

Advertisement