将文件数据写入类?c++

Writing file data into a class? C++

本文关键字:c++ 文件 数据      更新时间:2023-10-16

我有一个类,看起来像这样:

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的简单示例代码与示例输入完成投票。也就是说,我个人更希望您保留原始代码,因为如果其他人遇到这个问题,可以更容易地理解您的原始问题是什么。