c++,为什么文件读取进string失败,并且主函数返回值异常?

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char const *argv[])
{
    string s;
    cout << "creat str!" << endl;
    fstream f("a.txt", ios::in|ios::binary);
    if (!f)
    {
        cout << "open file faild" << endl;
        return 1;
    }
    cout << "open file." << endl;
    f.read((char*)&s, sizeof(s));
    cout << "read."<< endl;
    cout << s << endl;
    return 0;
}

输出:

其他一切正常,其中a.txt内容:

 

 就是输出不了string s的内容.请问是为啥?怎么改?

string类型不能直接强转为char*类型。

string类型转char*可以使用string提供的函数c_str() ,或是函数data(),不过这些都是临时指针,而且是const char *的临时指针,不能直接使用,一般用作函数参数或右值赋值使用。

这里可以使用 char* 类型,或者使用其他容器进行强转,比如:

    char * buffer = new char [length];
    is.read (buffer,length);
    // 或
    std::vector<char> buff(length, 0);
    in.read((char*)(&buff), length);

相关参考:http://www.cplusplus.com/reference/istream/istream/read/?kw=read

 抱歉,上面的代码打错了,使用vector<>时,从&buff[0]的位置存入读取内容。

    std::vector<char> buff(length, 0);
    in.read((char*)(&buff[0]), length);

因为vector<>数组实现机制是连续的空间,所以可以直接强转为char*进行读取。