2015-12-28 60 views
1

我遇到問題。C++結構不起作用

struct Info{ 
    string name; 
    string lastname; 
    int BirthDate[]; 
    int DeathDate[]; 
}human[2]; 
...... 

    for(int j=0; j < 3; j++){ 
     ReadFromFile >> human[0].BirthDate[j]; 
    } 
...... 

當我運行這個,我的編譯器停止工作。 但是,如果我改變

for(int j=0; j < 3; j++){ 
     ReadFromFile >> human[0].BirthDate[j]; 
    } 

要:

for(int j=0; j < 3; j++){ 
     ReadFromFile >> human.BirthDate[j]; //Removing array from struct too 
    } 

,一切工作正常。所以我的問題是有可能以某種方式與數組做?例如,我有2個人,我想從文件中讀取他們的BirthDate。我不能讓2個變量,因爲我不知道我的文件中有多少人。

+7

零長度數組是非法的C++。 – NathanOliver

+2

設計評論:爲什麼一個人會有超過一個的生日和死亡日期?我知道惡棍在很多電影中都有一條線,「*我有多少次要殺你。」*儘管一些信仰系統說人可以重生,所以這可能是你的原因。 –

+0

@ThomasMatthews日期的寫法如下:2015 12 28.我只是想把這個日期放入數組大小爲3的日期 – MonaXPusbroliS

回答

3

對於BirthDateDeathDate不需要數組嗎?

另外:你j計數至3。

試試這個:

struct Info{ 
    string name; 
    string lastname; 
    int BirthDate; 
    int DeathDate; 
} human[2]; 
...... 

    for(int j=0; j < 2; j++){ 
     ReadFromFile >> human[j].BirthDate; 
    } 
...... 

更新

出生日期包含這樣的:在2015年的文件12 28。

正如托馬斯·馬修斯說:

struct MyDate { 
    unsigned int year; 
    unsigned int month; 
    unsigned int day; 
}; 

struct Info{ 
    string name; 
    string lastname; 
    MyDate BirthDate; 
    MyDate DeathDate; 
} human[2]; 
...... 

    ReadFromFile >> human[0].BirthDate.year; 
    ReadFromFile >> human[0].BirthDate.month; 
    ReadFromFile >> human[0].BirthDate.day; 
...... 
+0

BirthDate包含如下所示的內容:2015 12 28文件 – MonaXPusbroliS

+1

如何在日期中使用'struct'?類似'struct Date(unsigned int year; unsigned int month; unsigned int day;};'。這將解決需要數組的問題;並且更具可讀性。 –

+0

@ThomasMatthews非常感謝答案:) – MonaXPusbroliS

2

做這樣的事情:

struct Date{ 
    int day; 
    int month; 
    int year; 
}; 
struct Info{ 
    string name; 
    string lastname; 
    Date BirthDate; 
    Date DeathDate; 
}human[2]; 


ReadFromFile >> human[0].BirthDate.day; 
ReadFromFile >> human[0].BirthDate.month; 
+0

致OP:你有沒有讓運營商超載? 'std :: istream&operator >>(std :: istream&stream,Date&date){return stream >> date.day >> date.month >> date.year; }'那麼你可以寫'ReadFromFile >> human [0] .BirthDate;' –

+0

是的,重載>>是個好主意。 –

+1

但是,寶貝的步驟......沒有人可以一次學習所有的C++。 –