Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
November 7th, 2002, 11:20 PM
 Michael_Bray
Contributing User

Join Date: Sep 2000
Location: Sydney, NSW, Australia
Posts: 40
Time spent in forums: < 1 sec
Reputation Power: 14
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
November 8th, 2002, 02:03 PM
 justin_dago
Contributing User

Join Date: Apr 2002
Location: new york
Posts: 84
Time spent in forums: < 1 sec
Reputation Power: 12
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
November 8th, 2002, 02:17 PM
 ClayDowling
Contributing User

Join Date: Oct 2002
Location: Flint, MI
Posts: 328
Time spent in forums: 1 h 19 m 25 sec
Reputation Power: 12
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.