繁体   English   中英

从二进制文件读取以null结尾的字符串C ++

[英]Reading a null terminated string from a binary file c++

如标题所述,我正在尝试从二进制文件中读取以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;
    }
}

使用std::getline

#include <string> // for std::getline

std::string ObjElement::ReadStringFromStream(std::ifstream &stream) {
    std::string s;
    std::getline(stream, s, '\0');
    return s;
}

使用getline并传递\\0 (空字符)作为分隔符。

get()函数返回对该流的引用,而不是已放入ch的字符。

您需要测试ch是否为'\\ 0'。

get函数返回流的引用,而不是读字符。

修改代码,例如:

std::string ObjElement::ReadStringFromStream(std::ifstream &stream) {
    std::string result = "";
    while (stream.get(ch)) { // exit at EOF
        if (ch != '\0')
            result += ch;
        else
            break;  // Stop the loop when found a '\0'
    }
    return result; 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM