簡體   English   中英

長字符串類型未正確保存

[英]Long string type not saving properly

我正在編寫一個程序來將 email 地址保存在 a.dat 文件中。 我將 email 聲明為“字符串 Email;” 並使用將 Email 保存在 a.dat 文件中

ofstream my_file;
my_file.open("Email.dat", ios::in | ios::out | ios::app | ios::binary);
while (!my_file.eof())
{
    p11.Email = Email;
    break;
}

my_file.write((char*)&p11, sizeof(p11));
cout << endl << endl << p11.Email << endl; // just to see if its saving the email properly
my_file.close();

(這里p11是一個 class 具有 Email 變量)

My problem is, whenever I am saving a long string, the p11 Email stores the Email properly, But when I find the Email from the.dat file using file handling again, I notice that for a long Email address it prints a lot of bars作為 output。 我還將添加一個屏幕截圖。

在此處輸入圖像描述

在此處輸入圖像描述

你不能做(char*)&p11 p11.Email內部隱藏了指向字符串 memory 的指針。

您應該執行以下操作:

ofstream my_file;

// ... write other parts of p11

// write the email length
int l = p11.Email.length();
my_file.write(&l, sizeof(l));

// write the email content
my_file.write(p11.Email.c_str(), l);

您也需要重寫讀取,首先讀取長度,調整字符串大小,然后讀取字符串。

但序列化本身就是一個完整的話題。 特別是如果您想在開始時進行二進制處理。 結構的填充和打包以及您是想在同一台機器上還是在不同的機器上讀取它都有一些注意事項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM