gpt4 book ai didi

C++ std::string length() 或 size() 不适用于方法参数

转载 作者:太空宇宙 更新时间:2023-11-04 16:24:31 34 4
gpt4 key购买 nike

我有一个方法可以从文件路径创建一个 MatLab 数组名称并将其作为 std::string 返回。结果字符串被传递到另一个方法,该方法将名称写入文件。当我尝试获取传入的字符串的长度时,当字符串的长度为 12 或 13 个字符时,它显示 0。

我的代码:

bool MyClass::masterMethod(std::string fileURI){

FILE* dataStream;
// Assume dataStream is set up correctly

// Get arrayName from File URI
std::string arrayName = this->makeArrayNameFromPath( fileURI);

//Write array name to file
this->writeArrayName(arrayName , dataStream)



}


std::string MyClass::makeArrayNameFromPath(std::string filePathURI){


std::string tempString = filePathURI.substr(filePathURI.find_last_of('/')+1);

std::string returnString = "";

long index = 0;

for(long i = 0; i < tempString.length(); i++){

if((tempString[i] != ' ') && (tempString[i] != '.')){

returnString[index++] = tempString[i];
}
}

return returnString;

}



void MyClass::writeArrayName(std::string name , FILE *nameStream){

// long testLength = name.length();
// long testLength2 = name.size();
// const char* testChar = nam.c_str();
// long testCharLen = strlen(testChar);

// The size of the name is the number of Chars * sizeof(int8_t)
int32_t sizeOfName = (int32_t)(name.length() * sizeof(int8_t));
int32_t nameType = miINT8;

fwrite(&nameType , sizeof(int32_t) , 1 , nameStream);
fwrite(&sizeOfName, sizeof(sizeOfName), 1, nameStream);
fwrite(&name , sizeof(name[0]), sizeOfName , nameStream);

}

所以我不确定为什么 string::length 不起作用。如果创建一个 std::string test = name,并打印它,我可以得到字符串的值,但不能得到它的长度或大小。如果我使用 const char* testName = name.c_str(); long test = strlen(testName),我得到一个正确的值,但认为没有必要。

因此,我们将不胜感激。

最佳答案

returnString[index++] = tempString[i]; 并不像您认为的那样。它不会为字符串添加额外的空间或长度,只会在字符串实际不拥有的位置覆盖内存。我认为 returnString.append(1, tempString[i]) 或类似的应该这样做。

关于C++ std::string length() 或 size() 不适用于方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13403862/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com