如标题所述,我正在尝试从二进制文件中读取以null终止的字符串。
std::string ObjElement::ReadStringFromStream(std::ifstream &stream) {
std::string result = "";
char ch;
while (stream.get(ch) != '\0') {
result += ch;
}
return result; }
我的空字符是“ \ 0”
但是,每当我调用该方法时,它都会读取到文件末尾
std::ifstream myFile(file, std::ios_base::in | std::ios_base::binary);
myFile.seekg(startByte);
this->name = ObjElement::ReadStringFromStream(myFile);
知道我在这里做错了什么吗?
istream::get(char &)
返回对的引用istream
,而不是读取的字符。您可以istream::get()
像这样使用变体:
while ((ch = stream.get()) != '\0') {
result += ch;
}
或将返回的流引用用作bool
:
while (stream.get(ch)) {
if (ch != '\0') {
result += ch;
} else {
break;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句