【发布时间】:2019-09-18 06:45:49
【问题描述】:
好的,所以我在大学的第二学期已经完成了 c 并且现在正在做 c++ 在 DevC 中做项目。
目前我正在制作一个程序,该程序将在拥有和编辑数据库的同时执行商店的收费过程。
尝试写入和读取一个完整的结构,但工作量不大,所以我写下 2 个 int 数字并读取它们,但这在读取时获得随机数时也能工作,即使我写 txt 数字看起来还可以。
//write and read are different fucntion only 1 is called .
//file creation code
int AccountNumber=0;
ofstream FileCreator("Database.dat",ios::binary);
FileCreator<<AccountNumber;
AccountNumber=1;
FileCreator<<AccountNumber;
和
//reading code
int AccountNumber=0;
ifstream FileCreator("Database.dat",ios::binary);
FileCreator.seekg(0,ios::beg);
FileCreator.read(reinterpret_cast<char*>(&AccountNumber), sizeof(AccountNumber));
cout<<AccountNumber<<endl;
FileCreator.read(reinterpret_cast<char*>(&AccountNumber), sizeof(AccountNumber));
cout<<AccountNumber<<endl;
我希望输出为 0 和 1,但得到的是 12592 和 12592。
【问题讨论】:
-
对于二进制写入,使用
std::ostream::write,而不是operator<<。因此,FileCreator<<AccountNumber应替换为FileCreator.write((char *) &AccountNumber, sizeof(AccountNumber))。 -
你的意思是你期望 0 和 1(不是 50)
-
你好 EJLH。无关,但您可能会感兴趣:minimal reproducible example.
-
@ThomasMatthews ooof 修复了它,谢谢:D。但为什么重要?
-
以二进制打开仅在 Windows 下有用,不会将 \n 即时转换为 \c\n