Monday, July 27, 2009

C++: How to make the sprintf built-in function not return a value?

This is my simple program for generation random numbers:





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;stdio.h%26gt;


using namespace std;





int main()


{


long seed=469858634;//default=123456789 9 digits


char pouch[20];





ofstream myfile;


myfile.open ("conv.txt");





while (0==0)


{


seed=seed*seed;





sprintf(pouch, "%d", seed);


seed=( (pouch[3]*1000)+(pouch[4]*100)+(pouch[5]... );





myfile %26lt;%26lt; seed %26lt;%26lt; "\n";


cout %26lt;%26lt; seed %26lt;%26lt; "\n";


}





system ("PAUSE");


return 0;





}





in each iteration, sprintf returns the number of characters written into the buffer, how do i make it not return this, because this is making my program add a 5 or a 6 to the beginning of each number

C++: How to make the sprintf built-in function not return a value?
I don’t think that your problem is the value returned by sprintf. It is true that sprintf is returning the number of characters printed, but in your program this value is not stored in any variable, and it’s lost.





The reason you have a 5 or a 6 in front of each number is the (pouch[3]*1000) expression which will NOT multiply the digit contained in pouch[3] with 1000, but the ASCII code of the digit contained in pouch[3] with 1000. Because pouch[3] is a character representing a digit, it will have values in the range 0x30 – 0x39 or 48-57 decimal. Multiplied with 1000, the result will be in the 48000-58000 range all the time.


For example if pouch[3]=’4’, the value of pouch[3]*1000 = 52000 and not 4000. If you want to multiply the digit instead of the ASCII code of the character stored, the correct expression will be:





((pouch[3]-0x30)*1000)+((pouch[4]-0x30)*...





And, of course you cannot make sprintf not return a value, because it’s build in, but is not a problem. If you don’t store it the program is not using it.
Reply:Why don't you use the rand() and srand() functions for generating random numbers?


No comments:

Post a Comment