-
strcat problems
Hello,
I am trying to strcat 3 strings, and am having a problem i cant figure out..
One of the string is originally an integer (i), so i am using itoa to convert to a char for the strcat.
Heres my code:
Code:
for(i=0;i<100;i++)
{
char buffer [33];
itoa (i,buffer,10);
char *numname;
numname=strcat("im", buffer);
cout<<"numname: "<<numname<<" ";
outputname=strcat(numname, ".png");
cout<<"outputname: "<<outputname<<" ";
}
now i was expecting output of the form:
numname: im0 outputname: im0.png
numname: im1 outputname: im1.png
numname: im2 outputname: im2.png
wheras i actually get:
numname: im0 outputname: im0.png
numname: im01 outputname: im01.png
numname: im012 outputname: im012.png
I cant seem to figure out the problem.
any help on this would be gratefully recieved.
Rob
-
Use would have to use strcpy followed by strcat. Think of what each is responsible for. I don't even want to guess why you are doing this though.
-
char *numname: this pointer points to dragons and evil imps. you need to allocate memory for it by either:
declaring an array:
char numname[20];
using malloc (which is depreciated in c++ i think):
char *numname;
numname = (char *) malloc (sizeof (char) * 20);
using new:
char *numname;
numname = new char[20]; // don't quote me on this, i'm a C programmer, not a C++ one :)
now this doesn't have to do with your problem, but its VERY VERY VERY bad form. your program happens to run at all because the dragons and imps that you pointed to are being nice today.
-
Code:
char numname[256];
char outputname[256];
for(i=0;i<100;i++)
{
sprintf(numname,"im%03d", i);
cout << "numname : " << numname << endl;
sprintf(outputname,"%s.png", numname);
cout << "outputname : " << outputname << endl;
}
I prefer to use sprintf as you can format the string better, eg :
sprintf(numname,"im%03d",i);
will give the output as :
numname : im000
outputname : im000.png
numname : im001
outputname : im001.png
...
numname : im099
outputname : im099.png
At least all the names will have the same length then.
-
thx quagsire, that does the job nicely.
moi, thx for the tip, i am new to c/c++ and am not used to setting aside memory etc..
the reason i want to do this is just to modify filenames for some pngs and jpgs i am outputting. There isnt a fixed number of these so its necessary to put a number in the names..
thx guys
Rob