从文件中导入输入并将其保存到临时存储器中? [英] takin input from a file and saving it into temporary memory?

查看:174
本文介绍了从文件中导入输入并将其保存到临时存储器中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a structured array that is initially empty and has 4 data types withing, string, 2 int's and 1 float. I have a list of dvd titles and other attributes (3 other,2 of them are int the last one is float) saved in a text file and I need to input the data from the text file to my structure. this is my code, but seems like it isnt working?

        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());


推荐答案

getline 是您读取的流,而不是您读取数据的字符串。

The return from getline is the stream you read from, not the string you read data into.

您也会重复读取数据到同一个地方

You're also repeatedly reading data into the same place (line), without saving it anywhere.

你的循环是有缺陷的( while(!somefile。

Your loop is defective (while (!somefile.eof()) is essentially always broken).

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

What you typically want is to start by overloading operator>> to read a single logical item from a stream, then use that to fill a vector of those items.

// 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>());

这篇关于从文件中导入输入并将其保存到临时存储器中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆