### Thread: Convert an integer to a cstring.

1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2000
Location
Sydney, NSW, Australia
Posts
40
Rep Power
17

#### 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.
2. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2002
Location
new york
Posts
84
Rep Power
16
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. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2002
Location
Flint, MI
Posts
328
Rep Power
15
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.