如何将结构推回到向量中

时间:2017-01-28 02:53:20

标签: c++

using namespace std;
struct Movie {
    string title;
    string director;
    string genre;
    string yearRelease;
    string duration;
};
int main(){
    cout << "Hi";
    ifstream fin;
    string line;

    vector <Movie> m;
    fin.open("Movie_entries.txt");
    while (getline(fin, line)) {
        cout << line << endl;
        stringstream lineStream(line);
        getline(lineStream, m.title, ',');
        getline(lineStream, m.director, ',');
        getline(lineStream, m.genre, ',');
        getline(lineStream, m.yearRelease, ',');
        getline(lineStream, m.duration, ',');
        m.push_back({title, director, genre, yearRelease, duration});
    }
}

我正在尝试将结构推回到向量中以存储我的数据,并且在如何做到这一点时遇到了麻烦。这就是我现在所拥有的。

1 个答案:

答案 0 :(得分:2)

您只需要创建一个struct变量;为它设置属性;然后将该结构推送到向量。

在C ++中,使用Movie aMovie;声明一个struct变量就足够了。无需struct Movie aMovie;

using namespace std;
    struct Movie {
        string title;
        string director;
        string genre;
        string yearRelease;
        string duration;
    };
int main(){
    cout << "Hi";
    ifstream fin;
    string line;

    vector <Movie> m;
    fin.open("Movie_entries.txt");
    while (getline(fin, line)) {
        cout << line << endl;
        stringstream lineStream(line);
        struct Movie aMovie;
        getline(lineStream, aMovie.title, ',');
        getline(lineStream, aMovie.director, ',');
        getline(lineStream, aMovie.genre, ',');
        getline(lineStream, aMovie.yearRelease, ',');
        getline(lineStream, aMovie.duration, ',');
        m.push_back(aMovie);
    }
}