如何从文本文件读取数据并推回向量? [英] how do i read data from textfile and push back to a vector?
问题描述
我有一个文本文件"test.txt",它按如下方式存储我的数据,每个定界符字段之间都有一个空格.
I have a text file, "test.txt" which stored my data as follow, there's a spacing between each delimiter field..
代码:名称: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
推荐答案
正如其他人已经指出的那样,一个问题是您正在将数据读入局部变量(code
,name
和coy
) ,但是在将它们添加到向量之前,切勿将这些值放入machine
中.
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.
那不是唯一的问题.您的while (!infile.eof())
也是错误的(实际上,while (!whatever.eof())
本质上总是 错误).您通常想做的是在阅读成功后继续阅读. whatever.eof()
仅在您尝试进行读取并且在开始读取之前 到达文件末尾时才返回true.
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.
我通常会解决的方法是为您的Machine类定义流提取器:
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>());
...,这将从文件中读取所有数据(使用我们在上文中定义的operator>>
)并将其用于初始化machines
向量.
...and that will read all the data from the file (using the operator>>
we defined above) and use it to initialize the machines
vector.
这篇关于如何从文本文件读取数据并推回向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!