举报

C++账单管理系统在文件二进制数据序列化读入和输出出现问题,求大佬解惑

0

    这里有问题,std::cerr << "长度" << passwordLength << std::endl;//如果前文写入的长度是10,此处会输出2573 ,然后输出后文的“2222”,可能是项目其他地方出现问题,可能需要帮我调试一下项目代码,还没写完,不到200行代码,好调试

std::ostream& operator<<(std::ostream& os, const BillManagementSystem& bms) {
    // 加密密码
    std::string temp = bms.password;
    for (auto& i : temp) {
        i ^= 6;
    }

    // 写入密码长度
    os.seekp(0,std::ios::beg);
    size_t passwordLength = temp.length();
    os.write(reinterpret_cast<const char*>(&passwordLength), sizeof(passwordLength));
    // 写入密码内容
    os.write(temp.c_str(), passwordLength);
}
// 重载输入运算符,用于反序列化
std::istream& operator>>(std::istream& is, BillManagementSystem& bms) {
    // 读取密码长度
    size_t passwordLength;
    is.read(reinterpret_cast<char*>(&passwordLength), sizeof(passwordLength));
    if (!is.good()) {
        is.setstate(std::ios::failbit); // 设置失败标志
        //std::cerr << "11111" << std::endl;
        return is;
    }
    // 读取密码内容
    std::string encryptedPassword(passwordLength, '\0');
    is.read(reinterpret_cast<char*>(&encryptedPassword[0]), passwordLength);
    std::cerr << "长度" << passwordLength << std::endl;//如果前文写入的长度是10,此处会输出2573 ,然后输出后文的“2222”
    if (!is.good()) {
        is.setstate(std::ios::failbit); // 设置失败标志        
        std::cerr << "2222" << std::endl;
        return is;
    }  
    // 解密密码
    for (auto& i : encryptedPassword) {
        i ^= 6;
    }
    bms.password = encryptedPassword;
    if (!is.good()) {
        is.setstate(std::ios::failbit); // 设置失败标志
        std::cerr << "3333" << std::endl;
        return is;
    }

}

ava
有毒

2025-2-13

悬赏金额:¥5元

1. 回答问题后,可以看到提问者联系方式。

2. 如果对问题有不明确的地方,可以在回复中写下你的疑问,就可以看到提问者的联系方式,然后详细沟通。

3. 如果私下沟通解决了问题,建议回答者将解决方案补充到本站,提问者勾选正确答案。每个人回答的问题数量,是能力的象征。

4. 回答问题后,可以通过提问者的联系方式私下协商领取悬赏的方式,本站不做任何干涉,不做担保,不抽取佣金,请双方谨慎操作。

举报
0

参考:

#include <iostream>
#include <fstream>

using namespace std;

void write() {
	FILE* pf;
	fopen_s(&pf, "F:\\test.txt", "w");

	string temp = "dkigjvngjd";
	for (auto& i : temp) {
		i ^= 6;
	}

	filebuf buf(pf);
	ostream os(&buf);
	os.seekp(0, std::ios::beg);

	size_t passwordLength = temp.length();
	os.write(reinterpret_cast<const char*>(&passwordLength), sizeof(passwordLength));
	// 写入密码内容
	os.write(temp.c_str(), passwordLength);
}

void read() 
{
	FILE* pf;
	fopen_s(&pf, "F:\\test.txt", "r");
	filebuf buf(pf);
	istream is(&buf);

	if (!is.good())
		cout << "error" << endl;

	size_t passwordLength = 10;
	is.read(reinterpret_cast<char*>(&passwordLength), sizeof(passwordLength));
	cout << passwordLength << endl;

	std::string encryptedPassword(passwordLength, '\0');
	is.read(reinterpret_cast<char*>(&encryptedPassword[0]), passwordLength);
	cout << encryptedPassword.c_str() << endl;
}


void main()
{
	//write();
	read();
}
ava
xiongfj ◑◑

2025-2-18

技术讨论社区