Tuesday, July 14, 2009

Help me with this program!! code inside, for making multiple filenames acording to an int value!?

#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


#include %26lt;fstream%26gt;


using namespace std;


int main ()


{


int a,b=0;


string fileN="";


ofstream record;


cout %26lt;%26lt; "Enter number of archives:";


cin %26gt;%26gt; a;


while (b %26lt; a)


{


fileN=b + ".txt";


b++;


record.open (fileN.c_str());


record %26lt;%26lt; "probandolo"%26lt;%26lt;b;


cout %26lt;%26lt; "probandolo"%26lt;%26lt;b%26lt;%26lt;"\n";


record.close();


}


return (0);}

Help me with this program!! code inside, for making multiple filenames acording to an int value!?
You can't just add strings together with the '+' operator. You need to create or use a function which can stitch 2 strings together.


There is a C function called strcat() which will do the job. Also, you need an ASCII representation of a decimal number. Use a function like itoa() to convert an integer into a string representation of a number.





Example:


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


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


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


char emptystring[16];


char name[]="Myfile";


char numeral[5];


int number=40;


char ext[]=".txt";





int main(void)


{


strcpy(emptystring, name); // copy 'name'


itoa(number, numeral, 10); // convert to str


strcat(emptystring, numeral); // append str


strcat(emptystring, ext); // append str


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


return 0;


}





strcat() and strcpy() requires string.h, and itoa() requires the stdlib.h header file. Look in your compiler's help file for more information on these functions.


No comments:

Post a Comment