how do i read data from textfile and push back to a vector?

徘徊边缘 提交于 2019-12-02 18:11:36

问题


I have a text file, "test.txt" which stored my data as follow, there's a spacing between each delimiter field..

Code: Name: Coy

045: Ted: Coy1
054: Red: Coy2

How do i read this data from file and insert this into a vector?

vector <Machine> data;
Machine machine

void testclass(){
ifstream inFile("test.txt");
if (!inFile){
    cout << "File couldn't be opened." << endl;
    return;
}
while(!inFile.eof()){
    string code,name,coy;
    getline(inFile,code, ':');
    getline(inFile,name, ':');
    getline(inFile,coy, ':');
data.push_back(machine)

}

but it seems to have a problem with pushing the data


回答1:


As others have already pointed out, one problem is that you're reading the data into local variables (code, name and coy), but never putting those values into the machine before you add it to the vector.

That's not the only problem though. Your while (!infile.eof()) is wrong as well (in fact, while (!whatever.eof()) is essentially always wrong). What you normally want to do is continue reading while reading was successful. whatever.eof() will only return true after you try to do a read and you've reached the end of the file before the read commenced.

The way I'd normally fix that would be to define a stream extractor for your Machine class:

class Machine { 
// ...

    friend std::istream &operator>>(std::istream &is, Machine &m) { 
        std::getline(is, m.code, ':');
        std::getline(is, m.name, ':');
        std::getline(is, m.coy, ":");
        return is;
    }
};

Using this, you can do your reading something like this:

std::vector<Machine> machines;

Machine machine;

while (infile >> machine) 
    machines.push_back(machine);

Once you've defined a stream extractor for the type, there's another possibility to consider as well though; you can initialize the vector from a pair of iterators:

std::vector<Machine> machines((std::istream_iterator<Machine>(infile)),
                               std::istream_iterator<Machine>());

...and that will read all the data from the file (using the operator>> we defined above) and use it to initialize the machines vector.




回答2:


you should read the data and put them into member variables of an object of Machine class. and then put that object on the Vector.



来源:https://stackoverflow.com/questions/14545120/how-do-i-read-data-from-textfile-and-push-back-to-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!