用ifstream读取文件中的内容然后保存到了字符串buff中,但是打印buff之后后面出现了别的东西,不知道为啥子

        string filename;
        cout << "请输入文件名字:";
        cin >> filename;
        ifstream t;
        
        int size;
        t.open(filename);
        t.seekg(0, ios::end);
        size = t.tellg();
        t.seekg(0, ios::beg);
        char* buffer = new char[size+1];
        t.read(buffer, size);
        t.close();

        string buff = buffer;
        
        cout << "....." << endl;
        cout << buff << endl;
        cout << "....." << endl;

下面是运行的结果,为啥子后面会多了乱七八糟的东西

img

下面是文件information.txt中的内容

img

我猜文件最后一行没有回车换行符。cout<<buff的时候是要一直输出到发现\0的,所以应在string buff = buffer;之前,将buffer最后一个字节变成\0:

        string filename;
        cout << "请输入文件名字:";
        cin >> filename;
        ifstream t;
        int size;
        t.open(filename);
        t.seekg(0, ios::end);
        size = t.tellg();
        t.seekg(0, ios::beg);
        char* buffer = new char[size+1];
        t.read(buffer, size);
        t.close();

        buffer[size]='\0';
        string buff = buffer;
        cout << "....." << endl;
        cout << buff << endl;
        cout << "....." << endl;

我觉得,是这一句话

t.open(filename);

里面的参数最好不是string类型,应当是传统的c风格字符数组。在我的电脑上运行,就有warning。

第15行改为:

string buff = string(buffer);

img
试一下改成size

参考: C++文件读写详解(ofstream,ifstream,fstream) https://www.cnblogs.com/hdk1993/p/5853233.html

代码修改如下,供参考:

    string filename;
    cout << "请输入文件名字:";
    cin >> filename;
    ifstream t(filename,ios::in|ios::binary);
    int size;
    //t.open(filename);
    t.seekg(0,ios::end);
    size = t.tellg();
    t.seekg(0,ios::beg);
    char* buffer = new char[size];
    t.read(buffer, size);
    t.close();
    string buff = string(buffer);
    cout << "....." << endl;
    cout << buff << endl;
    cout << "....." << endl;