我有一个 C++ 函数,它将 LPSTR 类型变量拆分为一个字符数组 (char*) 示例:
this->XMeshTexturePath = FindTexturePath(XMeshTexturePath,d3dxMaterials[i].pTextureFilename);
//the value of XMeshTexturePath is: Models\\Textures\\
//the value of d3dxMaterials[i].pTextureFilename is: BlaBlaBla\\BlaBla\\Cyrex.x
//The Result(XMeshTexturePath) should be like this:"Models\\Textures\\Cyrex.x"
这是我要写的功能:
int FindTextLength(char* Text){
int length
h=0; for(int i=0;i
char* FindTexturePath( char* TexturePath ,LPSTR FileNameToCombine){
int FileLength=0;
int PathAndFileLength=0;
char *FileName = new char;
char *TexPathAndName = new char;
strcpy(TexPathAndName, FileNameToCombine);
PathAndFileLength = FindTextLength(TexPathAndName);
for(int i=0; i<PathAndFileLength; i++){
if( TexPathAndName[i] != NULL){
if(TexPathAndName[i] != '\\'){
FileName[FileLength] = TexPathAndName[i];
FileLength++;
}
else
FileLength = 0 ;
}else break;
}
int PathLength = FindTextLength(TexturePath);
char *Result = new char;
//==============>> // I also tryed this:char *Result = new char[PathLength+FileLength];
//==============>> // char *Result = new char();
for(int i=0; i<PathLength; i++){
if( TexturePath[0] != NULL){
Result[i] = TexturePath[i];
}
else break;
}
for(int i=0; i<FileLength; i++){
if( FileName[0] != NULL){
Result[PathLength + i] = FileName[i];
}
else break;
}
return **Result**; // The Problem is here It should be like this:
// "Models\\Textures\\Cyrex.x"
// But I'm taking one of these as result:
// "Models\\Textures\\Cyrex.x{"
// "Models\\Textures\\Cyrex.xu"
// "Models\\Textures\\Cyrex.xY"
// The last character is random... 8O(
}
实际上它并没有那么糟糕。问题是当我声明一个 char 数组(char *Result = new char;)时,它不知道长度是多少我在最终结果(结果)的末尾增加了一个额外的字符,我真的被困在这里如果您有任何想法或建议,请告诉我。感谢您的任何建议和回应。
解决方案是在函数末尾添加这个:
Result[i] = TexturePath[i];
}
else break;
}
for(int i=0; i<FileLength; i++){
if( FileName[0] != NULL){
Result[PathLength + i] = FileName[i];
}
else break;
}
Result[PathLength+FileLength] = '\0' ; // This part is resloving the problem.
// **Thanks for helps**.
return Result;
}