我在我的项目中将所有 char* 更新为 string 并且我被困在这个部分:
void Load(char* resourceName)
{
_fileReader.seekg(0);
while(_fileReader.tellg() < _FILE_SIZE)
{
int cResourceID = 0;
char* cResourceName = new char[_MAX_RESOURCE_NAME];
_fileReader.read((char*)&cResourceID, 4);
_fileReader.read((char*)cResourceName, _MAX_RESOURCE_NAME);
if(cResourceName == resourceName)
{
//Resource Found, do something
}
}
}
当我改为字符串时,我得到:
void Load(string &resourceName)
{
_fileReader.seekg(0);
while(_fileReader.tellg() < _FILE_SIZE)
{
int cResourceID = 0;
string cResourceName;
_fileReader.read((char*)&cResourceID, 4);
//I don't know how to do this:
_fileReader.read((char*)cResourceName, _MAX_RESOURCE_NAME);
//And nor this:
if(cResourceName == resourceName)
{
//Resource Found, do something
}
}
}
因为我总是在阅读 _MAX_RESOURCE_NAME 个字符,所以我的字符最终会像:"NAME !#$II#$II"(一堆未初始化的字符和/或空格),甚至比较(字符“NAME___ " == string " NAME”)也会失败 .
我可以像使用char *一样使用ifstream将X个字符读入字符串吗?
如何清除文件中的空格/未初始化字符以比较名称?
edit: 忘了添加它's a binary file and I can' t使用std :: getline()
1 回答
从文件中读取字符后,应在最后读取的字符后添加零(0x0或'\ 0') . 您的缓冲区大小应足够大以容纳零终止 .
在你的情况下,直接读入std :: string可能不是一个好主意 . 像以前一样将它读取到缓冲区,然后将char * buffer分配给string .