鍍金池/ 問答/C++/ C++文件讀出數據為亂碼

C++文件讀出數據為亂碼

一段很簡單的關于文件的問題,但是數據讀取不了,讀取結果為亂碼
代碼如下

include <fstream>

include <iostream>

include<string>

using namespace std;

class UserType
{
public:

void getCode(int s)
{
        k = s;
}
int select()
{
    return k;
}

private:

int k;

};

int main()
{

UserType U, T;
U.getCode(5);
ofstream outfile("1.txt", ios::ate | ios::binary);   //打開文件,設置寫入方式為覆蓋寫入

if (!outfile)
{
    cout << "txt文件打開失敗!" << endl;
    exit(0);
}
outfile.write((char*)&U, sizeof(U));
outfile.close();

ifstream outf("1.txt", ios::ate | ios::binary);
if (!outf)
{
    cout << "txt文件打開失敗!" << endl;
    exit(0);
}
outf.read((char*)&T, sizeof(T));
outf.close();

cout << T.select() << endl;
cout << "lalala" << endl;
getchar();
return 0;

}

而且,如果將代碼中的所有類中關于int類型變量k改為string類型,就連亂碼這樣的數據都拿不到,但是卻編譯成功了。

回答
編輯回答
落殤

這一行錯誤了,ios::ate定位到了文件末尾
ifstream outf("1.txt", ios::ate | ios::binary);

2018年1月29日 03:45