在从文件导入数据时遇到麻烦。我正在无休止的循环

问题描述 投票:0回答:1

我可以让我的文件加载1个完整结构。但是,当我尝试遍历文件时,我有一个无限循环,并且没有数据加载。我已经附上了我的代码和平面文件。

#include <iostream>
#include <string.h>
#include <vector>
#include <fstream>

using namespace std;

typedef struct video_items{
    string Title;
    int YOP;
    string Category;
    float Gross;
}video;

void LoadMovies (vector<video> &v);
void SearchMovies (vector <video> &v, string s);

int main()
{
    vector <video> v;

    LoadMovies(v);

    cout<<"Total number of movies: "<<v.size()<<endl;

    for (unsigned int i=0; i<v.size(); ++i) {
        cout<<"----------------------------------------------------"<<endl;
        cout<<v[i].Title<<endl;
        cout<<"Category: "<<v[i].Category<<endl;
        cout<<"Year of Publication: "<<v[i].YOP<<endl;
        cout<<"Gross: "<<v[i].Gross<<endl;
        cout<<"----------------------------------------------------"<<endl<<endl;
    }

    string WantMovie;
    cout<<"Please type in what movie you want."<<endl;
    cin>>WantMovie;
    SearchMovies(v,WantMovie);

    return 0;
}

void LoadMovies (vector<video> &v)
{
    video L;
    ifstream myfile;
    myfile.open ("Movies.txt");
    if (myfile.is_open())
    {
        cout <<"Loading Movie Catalog..."<<endl<<endl;
        int i=0;
        while (!myfile.eof())
        {
            myfile.ignore();
            //cout<<i<<endl<<endl;

            v.push_back(L);
            getline(myfile,v[i].Title);
            getline(myfile,v[i].Category);
            myfile>>v[i].YOP;
            myfile>>v[i].Gross;
            i++;
        }
        myfile.close();
    }
    else cout<<"Unable to open file."<<endl;
}

void SearchMovies (vector <video> &v, string s)
{
    s[0] = toupper(s[0]);
    unsigned int i;

    for (i=0; i<v.size(); i++)
    {
        if (v[i].Title.compare(0,s.size(),s)==0)
        {
            break;
        }
    }
    if (i >=v.size()){
        i =0;
    }
    switch(i)
    {
        case 1:cout<<"You have chosen "<<s<<endl;
        break;
        default:
        cout<<"That movie is not currently in the library, please choose a different one."<<endl;
        break;
    }
}

在平面文件中忽略第一个字符。

=========数据文件==========

 Captain America: The First Avenger
Action, Adventure, Sci-Fi
2011
1786.65
Iron Man
Action, Adventure, Sci-Fi
2008
585.2
The Incredible Hulk
Action, Adventure, Sci-Fi
2008
134.52
Iron Man 2
Action, Adventure, Sci-Fi
2010
312.43
Thor
Action, Adventure, Fantasy
2011
181.03
The Avengers
Action, Adventure, Sci-Fi
2012
623.28
Iron Man 3
Action, Adventure, Sci-Fi
2013
409.01
c++ codeblocks ifstream
1个回答
0
投票

如果仍然遇到问题,请考虑从数据文件读取每个结构必须完成的工作。您需要阅读4条信息,即2字符串,1-int,1-float。您正在考虑正确地读入临时结构L,但是您要做的是验证在将L添加到向量之前,您已经正确填充了L的所有四个成员。

© www.soinside.com 2019 - 2024. All rights reserved.