我試圖從一個文件加載一個名爲Friend的類的動態數組。 Friend類有兩個私有變量,一個用於名稱的字符串和一個Date類對象。我重載輸入操作符來調用這個函數,輸入朋友:如何從這個文件的不同行加載數據?
void Friend::input(std::istream& ins){
char tmpname[50];
bool x = false;
std::cout << "Please enter a name: ";
ins>>tmpname;
std::string tmpstring(tmpname);
name = tmpstring;
ins.sync();
std::cout << "\n\n" << "Please Enter a Birth date in MM/DD/YYYY format: ";
ins.sync();
ins >> bday;
ins.sync();
std::cout<<"\n\n";
}
也輸入運算符重載日期類有月,日和一年三個整數。下面是該代碼:
// input operator, overloaded as a friend
istream& operator >>(istream& ins, Date& d){
bool flag = false;
string junk;
ins>>d.month;
// if an invalid month is detected throw a bad_month
if(d.month < 1 || d.month > 12){
getline(ins,junk); // eat the rest of the line
throw (bad_month(d.month));
}
// if the read has failed because of eof exit funtion
if(ins.eof()) return ins;
if(ins.peek() == '/') ins.ignore();
ins>>d.day;
// if an invalid day is detected throw a bad_day
if(d.day < 1 || d.day > d.daysallowed[d.month]){
getline(ins,junk); // eat the rest of the line
throw (bad_day(d.month, d.day));
}
if(ins.eof()) return ins;
if(ins.peek() == '/') ins.ignore();
ins>>d.year;
return ins;
}
在一類,FBFriends,我有型朋友的動態數組,我需要從在啓動時加載的文件加載保存的名字和生日。該文件必須以這種格式:
First Last
MM/DD/YYYY
First Last
MM/DD/YYYY
First Last
MM/DD/YYYY
,我試圖加載功能是:
void FBFriends::load(std::istream& ins){
Friend f1;
int i=0;
while(ins >> f1){
if(i % 2 == 0 && i != 0){insert(f1);};
i++;
}
}
void FBFriends::insert(const Friend& f){
if(used >= capacity){ resize();}
for(int i = used; i>current_index; i--){
data[i] = data[i - 1];
}
data[current_index] = f;
used++;
}
我在很長的帖子道歉,我需要包括所有相關的代碼。加載函數將無效值插入導致崩潰的日期函數中。我怎樣才能正確地將這些值加載到Friend數組中?
爲什麼不直接在'tmpstring'或'name'中輸入名稱,以便輸入名稱超過49個字符時程序不會崩潰。 –
Didnt知道如何將值提取到字符串中。我基本上已經搞亂Friend :: input和FBFriends :: load ...我不知道即時消息在這兩個場所做什麼,儘管輸入函數在代碼的其他部分起作用,當我從鍵盤輸入時,不是文件。 – user2905256