I want to build a series of paths with serial numbers through a for loop, so I use a series of strcpy and strcat (I know there is a string method, but please forgive me, my technique is really poor). But after the loop, I get a series of the same results.
Here is my code:
#include <iostream> #include <io.h> #include <vector> vector<char*> TempFilePath; char temp[300]; strcpy(temp, EndFilepath); strcat(temp, "\\Temp"); createDirectory(temp); char TempFilePathChar[300]; for (int j = 0; j < filevector.size(); j++) { int number = j + 1; char TEMPNum[1]; itoa(number, TEMPNum, 10); strcpy(TempFilePathChar, temp); strcat(TempFilePathChar, "\\tempData"); strcat(TempFilePathChar, TEMPNum); strcat(TempFilePathChar, ".tif"); strcpy(TempFilePathChar, TempFilePathChar); TempFilePath.push_back(TempFilePathChar); } The EndFilepath="E:\\", the size of filevector is 2. Undoubtly, I'd like to get the result of flowing:
TempFilePath[0]="E:\\Temp\\tempData1.tif" TempFilePath[1]="E:\\Temp\\tempData2.tif" But after running, the result is like following:
TempFilePath[0]="E:\\Temp\\tempData2.tif" TempFilePath[1]="E:\\Temp\\tempData2.tif" Can someone tell me why and how to change it?
Note:I still want to use vector < char * > instead of vector < string >, because I use a lot of functions on the network, and their return value and input value are char * type. Of course, if there is a method, it can still achieve the above purpose. Thanks again
TempFilePath, it's essential to solving your problem. I'm guessing it'svector<char*>when it should bevector<string>.std::vector<std::string>instead ofstd::vector<char*>.char temp[300];buffer, with multiple pointers stored in the vector that all point to it. So it's natural that all of the pointers in the vector point to the same data (whatever is currently intemp)char TEMPNum[1]is too short; if you want it large enough to store one ASCII character, it needs to be at leastchar TEMPNum[2], so that you have one char for the digit and another char to hold the NUL-terminator byte. (and if you want it to store numbers with more than one digit in them, it needs to be bigger than that)