#include <iostream>
#include <string>
#include <fstream>
using namespace std;int main()
{
cout<<"Input:";
string input;
cin>>input;
ofstream ifile("c:/t.txt",ios_base::binary);
if(!ifile)
cout<<"ERROR:Failed to open the file."<<endl;
ifile.write((char *)&input,sizeof input);
ifile.close(); string output;
ifstream ofile("c:/t.txt",ios_base::binary);
if(!ofile)
cout<<"ERROR:Failed to open the file."<<endl;
ofile.read((char*)&output, sizeof output);
cout<<"Reading:"<<output<<endl;
ofile.close();
return 0;
}编译通过,运行时,若输入大于15个字符就会出错,提示_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)和其他两个错误。很奇怪啊,,请高手点解一下。。

解决方案 »

  1.   

    我用的是visual studio 2005
      

  2.   

    string是一个c++中已经封装好的类。
    这个string类,能自动调整大小,不能用sizeof()取其大小。因为他是个不定值。
    你要往文件里写内容的话,可以直接使用:
    ofile>>output;
      

  3.   

    我试了一下,如果把string input,string output全都改为char数组的话,就一切正常了,大小没有限制。是string 的话,就不能超过15个字符,挺奇怪的
    期待 N人们的到来。。
      

  4.   

    ifile.write((char *)&input,sizeof input); ——》ifile.write(input.c_str(), input.length()) 
    读不能用string,要先读到一个自定的char buff[nMax],然后把它转换为string
      

  5.   

    string output; 
    ifstream ofile("c:/t.txt",ios_base::binary); 
    if(!ofile) 
    cout < <"ERROR:Failed to open the file." < <endl; 
    ofile.read((char*)&output, sizeof output); 
    cout < <"Reading:" < <output < <endl; 
    ofile.close(); 
    return 0; 

    string是一个类,大小是固定的,里面保存指针,指针里面存的才是字符串
      

  6.   

    二进制打开文件的话,你还是用vector<char>;
    int main(int argc, char* argv[])
    {
    ifstream ifs( "temp", ios_base::binary);
    ifs.seekg( 0 , ios_base::end );
    size_t len = ifs.tellg();
    ifs.seekg( 0 , ios_base::beg );
    vector<char> vec(len+1);
    ifs.read( &vec[0],len );
    printf("%s",&vec[0]);
        return 0;
    }
      

  7.   


    大家说的挺对的啊收5楼启发,我写了一个小测验程序;
    //test_string.cpp#include <iostream>
    #include <string>
    using namespace std;int main()
    {
    string str;
    cout<<sizeof(str)<<endl;
    return 0;
    }
    输出为:32
    谢谢4楼的指导,我会改的。