在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/C++/ C++文件讀出數(shù)據(jù)為亂碼

C++文件讀出數(shù)據(jù)為亂碼

一段很簡單的關(guān)于文件的問題,但是數(shù)據(jù)讀取不了,讀取結(jié)果為亂碼
代碼如下

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);   //打開文件,設(shè)置寫入方式為覆蓋寫入

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;

}

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

回答
編輯回答
落殤

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

2018年1月29日 03:45