从二进制文件c ++中读取一个以null结尾的字符串

时间:2014-08-08 14:55:50

标签: c++ fstream

正如标题所说我试图从二进制文件中读取一个以空字符结尾的字符串。

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);

知道我在这里做错了吗?

5 个答案:

答案 0 :(得分:5)

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;
    }
}

答案 1 :(得分:3)

使用std::getline

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

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

答案 2 :(得分:2)

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

答案 3 :(得分:1)

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

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

答案 4 :(得分: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; 
}
相关问题