2015-09-24 18 views
1

我試圖從一個文件加載一個名爲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數組中?

+0

爲什麼不直接在'tmpstring'或'name'中輸入名稱,以便輸入名稱超過49個字符時程序不會崩潰。 –

+0

Didnt知道如何將值提取到字符串中。我基本上已經搞亂Friend :: input和FBFriends :: load ...我不知道即時消息在這兩個場所做什麼,儘管輸入函數在代碼的其他部分起作用,當我從鍵盤輸入時,不是文件。 – user2905256

回答

1

由於名稱佔用整行,因此請使用getline來讀取名稱。更換

ins>>tmpname; 
std::string tmpstring(tmpname); 
name = tmpstring; 

通過

getline(ins, name); 

更新

FBFriends::load,您有:

while(ins >> f1){ 

,如果你有一個函數

只會工作
std::istream& operator>>(std::istream& in, Friend& f) { ... } 

我建議你刪除

void Friend::input(std::istream& ins) { ... } 

std::istream& operator>>(std::istream& in, Friend& f) { ... } 

而且代替它,我不明白的

if(i % 2 == 0 && i != 0){insert(f1);}; 

的目的,我相信你知道你在那裏做什麼。

+0

那麼你如何閱讀日期?他們需要整數,而不是字符串,並且它們交替排列。 – user2905256

+0

您可以繼續使用現有代碼讀取日期。閱讀日期後,您必須確保您跳過換行符。有關詳細信息,請參閱[std :: istream :: ignore](http://en.cppreference.com/w/cpp/io/basic_istream/ignore)。 –

+0

用'getline()'讀取每一行,並使用'strstream'從包含數字的行讀取int。 – Barmar

相關問題