|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now! |
|
#1
|
|||
|
|||
|
Convert an integer to a cstring.
Hi,
I have a while loop that is going through a whole lot of numbers and doing calculations on them. 49493 returns 29 for example because if you do 4 + 9 + 4 + 9 + 3 you get 29. Therefore I want to create a file called 29.txt and add 49493 to it, and be able to add any other numbers in the loop that add up to 29 to it as well. I have the variable called sum which is the "29" in this example. In the loop i have the ins.open("sum.txt") and it literally opens up sum.txt instead of 29.txt I seem to remember hearing that I need to convert the sum to a cstring and then do the ins.open("sum.txt")... Any advice on an easy way to convert the integer to a cstring so that I can open a file based on the sum would be appreciated.
__________________
Cheers, Michael Bray |
|
#2
|
|||
|
|||
|
try
Code:
itoa(value, string, base); //////////////////////////////////////////////////////// // // value is the integer value to be converted // string is a pointer to the location in memory where the string is to be stored // number represents the base of the converted value: // (8 = octal, 10 = decimal, 16 = hexadecimal, etc.) // /////////////////////////////////////////////////////// you may have to #include <ctype.h> |
|
#3
|
|||
|
|||
|
This is the route I would take:
Code:
#include <stdio.h>
char* outfile;
int sum;
FILE* fout;
sum = mystryfunction(inputint);
asprintf(&outfile, "%d.txt", sum);
fout = fopen(outfile, "a");
if (fout) {
fprintf(fout, "%d\n", inputint);
fclose(fout);
}
else
perror(outfile);
free(outfile);
That's entirely C code, no attempt at C++. It's not as sexy, but your C++ compiler will take it (and like it), and the standard C library is remarkably good at handling situations like this. A word of explanation: when you learned C, your probably never saw the asprintf function. It's a recent addition to the stdc library, and older compilers/libraries might not support it (you'll never find it in Sun libraries, for example). It works just like sprintf, but you pass it a pointer to a pointer, and it will automatically allocate the necessary space for your string.
__________________
Clay Dowling Lazarus Notes Articles and commentary on web development http://www.lazarusid.com/notes/ |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > Convert an integer to a cstring. |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|