将文件数据写入类?c++
Writing file data into a class? C++
我有一个类,看起来像这样:
class Test
{
public:
Test() {}
~Test() {}
//I kept these public for simplicity's sake at this point (stead of setters).
int first_field;
int second_field;
int third_field;
string name;
};
我的。txt文件看起来像这样:
1 2323 88 Test Name A1
2 23432 70 Test Name A2
3 123 67 Test Name B1
4 2332 100 Test Name B2
5 2141 98 Test Name C1
7 2133 12 Test Name C2
我希望能够从文件的每一行读取到一个向量,所以我当前的代码看起来像这样:
#include "Test.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
ifstream file;
vector<Test> test_vec;
file.open("test.txt");
if(file.fail())
{
cout << "ERROR: Cannot open the file." << endl;
exit(0);
}
while(!file.eof())
{
string input;
if(file.peek() != 'n' && !file.eof())
{
Test test;
file >> test.first_field >> test.second_field >> test.third_field;
getline(file, input);
test.name = input;
test_vec.push_back(test);
}
}
return 0;
}
所以,我被困在我想要读取数据的部分…我试过输入流操作符,它不做任何事情;其他选项给我错误。如果可能的话,我还希望保留格式。接下来我想做的是能够根据类中的不同数据字段对向量进行排序。
任何想法?
EDIT:问题已经解决,代码已经被编辑以反映它。谢谢你的帮助。:)
在读取文件并将其解析为类的对象之前应该解决的一个问题是:
Test test;
test.push_back(test);
你的局部变量test
是类Test
的对象,它隐藏了你的向量:
vector<Test> test;
当你这样做的时候:
test.push_back(test);
你会有麻烦。请尝试使用不同的名称来命名您的对象。
现在您可以考虑如何处理每一行,您可以这样做:
ifstream file;
file.open("test.txt");
int first_field, second_field, third_field;
string testName;
while (!file.eof()) {
file >> first_field >> second_field >> third_field;
getline(file, testName);
cout << first_field <<" " << second_field << " " << third_field;
cout << endl << testName <<endl;
//you should set your constructor of Test to accept those four parameters
//such that you can create objects of Test and push them to vector
}
tacp的回答很好,但我认为有两件事更符合c++/STL:
使用operator >>
istream & operator>>(istream &in, Test &t)
{
in >> t.first_field >> t.second_field >> t.third_field;
getline(in, t.name);
return in;
}
此时文件中的读取看起来像这样
ifstream file("test.txt");
vector<Test> tests;
Test test;
while(file >> test) {
tests.push_back(test);
}
使用streamiterator
/迭代器构造函数
要使它超级符合stl风格,请使用istream_iterator
(不要忘记#include<iterator>
),并从迭代器构造vector
:
ifstream file("test.txt");
istream_iterator<Test> file_it(file), eos;
vector<Test> tests(file_it, eos);
PS:我为noocode的简单示例代码与示例输入完成投票。也就是说,我个人更希望您保留原始代码,因为如果其他人遇到这个问题,可以更容易地理解您的原始问题是什么。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到