首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 結構體數組輸出文件:ofstream 不支持直接輸出自定義結構體,需逐字段寫入

     編輯:程式設計綜合問答

錯誤代碼


struct point { float x, y; };
point D[800][600];
// ... 計算賦值 ...
ofstream ofile("D.txt");
for (int i=0; i<800; i++)
    for (int j=0; j<600; j++)
        ofile << D[i][j] << endl; // 編譯錯誤:無 operator<< 重載

修復:逐字段寫入或重載運算符

方案一:直接寫入字段(最簡單)


ofile << D[i][j].x << ' ' << D[i][j].y << '\n';

方案二:重載 operator<<(優雅、可復用)


struct point { float x, y; };
// 友元函數重載
friend ostream& operator<<(ostream& os, const point& p) {
    return os << p.x << ' ' << p.y;
}

// 使用
ofile << D[i][j] << '\n'; // 現在合法

方案二:二進制寫入(高性能、空間小)


// 寫入
ofstream ofile("D.bin", ios::binary);
ofile.write(reinterpret_cast(D), sizeof(D));

// 讀取
ifstream ifile("D.bin", ios::binary);
ifile.read(reinterpret_cast(D), sizeof(D));

注意:二進制格式跨平台/編譯器可能有對齊/字節序差異,僅用於同環境臨時存儲。

完整修正代碼片段


struct point { float x, y; };
point D[800][600];

// 計算...
for (int I=0; I<800; I++) {
    for (int J=0; J<600; J++) {
        D[I][J].x = -1000.0f * 1 * (I-400) / 50;
        D[I][J].y = -1000.0f * 1 * (J-300) / 50;
    }
}

// 文本輸出(可讀)
ofstream ofile("D.txt");
for (int i=0; i<800; i++) {
    for (int j=0; j<600; j++) {
        ofile << D[i][j].x << ' ' << D[i][j].y << '\n';
    }
}
ofile.close();

核心原則

C++ 流對象**只內置基本類型**的 operator<<,**自定義類型必須自行實現**序列化邏輯(文本或二進制)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved