大家好,在我之前的问题中,我能够将结构的数据加载到文件中,但现在的问题是我在检索它时得到了垃圾值。
文件内容:settings.bin
110#NormalCompression Level210#NormalCompression Level310#NormalCompression Level410#NormalCompression Level510#NormalCompression Level
代码
#include<cstdlib>
#include<iostream>
#include<string>
#include<iomanip>
#include<fstream.h>
using namespace std;
const char* ErrorLogFilePath = "resources\\error.txt";
const char* SettingsFilePath = "resources\\settings.bin";
const int NoOfSettings = 5;
struct Setting {
int SettingID;
int SettingINTValue;
double SettingDOUBLEValue;
char SettingCHARValue;
string SettingSTRINGValue;
string SettingName;
};
istream& operator>>(istream& _is, Setting& _s) {
_is>>_s.SettingID;
_is>>_s.SettingINTValue;
_is>>_s.SettingDOUBLEValue;
_is>>_s.SettingCHARValue;
_is>>_s.SettingSTRINGValue;
_is>>_s.SettingName;
}
ostream& operator<<(ostream& _os, const Setting& _s) {
_os<<_s.SettingID;
_os<<_s.SettingINTValue;
_os<<_s.SettingDOUBLEValue;
_os<<_s.SettingCHARValue;
_os<<_s.SettingSTRINGValue;
_os<<_s.SettingName;
}
class ErrorReport {
public:
fstream ErrorFile;
void PostError(string Title,string Data,int ErrorID) {
ErrorFile.open(ErrorLogFilePath,ios::out);
ErrorFile.close();
}
} Error;
class SettingsClass {
public:
Setting setting[NoOfSettings];
void ResetSettings() {
fstream SettingFile;
Setting defaultsetting[NoOfSettings];
for(int i=1; i<=NoOfSettings; i++) {
defaultsetting[i-1].SettingID = i;
defaultsetting[i-1].SettingINTValue = 0;
defaultsetting[i-1].SettingDOUBLEValue = 0;
defaultsetting[i-1].SettingCHARValue = '#';
defaultsetting[i-1].SettingSTRINGValue = "null";
switch(i) {
default:
defaultsetting[i-1].SettingName = "Compression Level";
defaultsetting[i-1].SettingSTRINGValue = "Normal";
defaultsetting[i-1].SettingINTValue = 1;
break;
}
}
SettingFile.open(SettingsFilePath,ios::binary|ios::out);
if(SettingFile.is_open()) {
for(size_t i=0; i<NoOfSettings; ++i) {
SettingFile<<defaultsetting[i];
}
} else {
cout<<"Error!";
}
SettingFile.close();
}
void _SettingsClass() {
fstream SettingFile;
SettingFile.open(SettingsFilePath,ios::binary|ios::in);
Setting TempSettings[NoOfSettings];
if(SettingFile.is_open()) {
for(size_t i=0; i<NoOfSettings; ++i) {
SettingFile>>TempSettings[i];
}
} else {
cout<<"Error...";
}
SettingFile.close();
for(int i=0; i<NoOfSettings; i++) {
cout<<TempSettings[i].SettingINTValue<<"\n";
}
}
} Settings;
int main(int argc, char *argv[])
{
Settings._SettingsClass();
// cout<<Settings.GetSetting(1).SettingName;
system("PAUSE");
return EXIT_SUCCESS;
}
输出
4473076
1
3
0
2686384
现在为什么我得到那些垃圾值?谁能帮助我,因为我认为它不应该像这样出现(?)。对于该结构数组的每个这样的元素,我应该得到 1。
提前致谢!