0

我有一个结构化数组,它最初是空的,有 4 种数据类型 withing、string、2 个 int 和 1 个 float。我有一个保存在文本文件中的 dvd 标题和其他属性列表(其他 3 个,其中 2 个是 int 最后一个是浮点数),我需要将文本文件中的数据输入到我的结构中。这是我的代码,但似乎它不起作用?

        do
        {
           for(int i=0;i<MAX_BOOKS;i++)
           {

                tempTitle= getline(myfile,line);
                temChapters = getline(myfile,line);
                tempReview = getline(myfile,line);
                tempPrice = getline(myfile,line);
           }
        }while(!myfile.eof());
4

2 回答 2

5

return fromgetline是您从中读取的流,而不是您将数据读入的字符串。

您还重复将数据读取到同一个位置 ( line),而没有将其保存在任何地方。

你的循环有缺陷(while (!somefile.eof())基本上总是坏的)。

您通常想要的是首先重载operator>>以从流中读取单个逻辑项,然后使用它来填充这些项的向量。

// The structure of a single item:
struct item { 
    std::string title;
    int chapters;
    int review;
    int price;    
};

// read one item from a stream:
std::istream &operator>>(std::istream &is, item &i) { 
    std::getline(is, i.title);
    is >> i.chapters >> i.review >> i.price;
    is.ignore(4096, '\n'); // ignore through end of line.
    return is;
}

// create a vector of items from a stream of items:
std::vector<item> items((std::istream_iterator<item>(myfile)), 
                         std::istream_iterator<item>());
于 2013-02-13T00:38:06.627 回答
0

你应该像这样构造它:

std::ifstream myfile("filename.dat");
std::string line;

while (getline(myfile, line))
{

    // you can use std::string::find(), std::string::at(), std::string::substr
    // to split the line into the necessary pieces

}

然后,您可以使用 Jerry coffins 答案将每个部分保存在vector<item>.

于 2013-02-13T00:51:01.927 回答