c ++从txt读取并解析为类struct

时间:2017-04-26 22:59:09

标签: c++ parsing fstream

在我需要从txt文件中读取的项目中,每三行都有我们所需的状态信息,我必须将信息解析到我创建的类中。我知道我需要一对for循环,但不知道如何格式化代码。

这是txt文件的格式:

New Hampshire
Concord
9304 1788 9
Massachusetts
Boston
8257 1788 6
Vermont
Montpelier
9609 1791 14

每三行包括需要解析的三个单独的整数。到目前为止,这是我的代码:

int main()
{

    ifstream file("Example_State_data.txt");
    string name;
    string capital;
    int area = NULL;
    int index = NULL;
    int addYear = NULL;
    int addOrder = NULL;

    hashFunc States;
    States.setStateInfo("Hawaii", "Honlulu", 0, 0, 0);
    States.printTable();

    if (file.is_open())
    {
        while (!file.eof())
        {
            file >> name;
            index++;

        }
        cout << index << " items found";
        file.close();
    }
    else
    {
        cout << "file is not open!";
    }
}

void hashFunc::setStateInfo(string name, string capital, int area, int 
admissionYear, int admissionOrder)
{
    int index = Hash(name);
    if (hashTable[index]->name == "empty")
    {
        hashTable[index]->name = name;
        hashTable[index]->capital = capital;
        hashTable[index]->area = area;
        hashTable[index]->admissionYear = admissionYear;
        hashTable[index]->admissionOrder = admissionOrder;
    }

1 个答案:

答案 0 :(得分:0)

如果您只是需要一种方法来读取数据并将其放在结构中,这是一个可以读取数据的示例:

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    ifstream inFile("Example_State_data.txt");
    if(!inFile.good()) { cout << "File read error" << '\n'; exit(1); }

    struct data
    {
        string name;
        string capital;
        int area;
        int addYear;
        int addOrder;
    };

    vector<data> all_data;

    data one;

    while
    (
        getline(inFile, one.name)
        &&
        getline(inFile, one.capital)
        &&
        inFile
            >> one.area
            >> one.addYear
            >> one.addOrder
    )
    {
        all_data.push_back(one);
        getline(inFile, one.name); // pass third line
    }


    // ---- Read back ---------
    size_t n = all_data.size();
    for(size_t i = 0; i < n; ++i)
    {
        cout
            << all_data[i].name << '\t'
            << all_data[i].capital << '\t'
            << all_data[i].area << '\t'
            << all_data[i].addYear << '\t'
            << all_data[i].addOrder << '\n';
    }
    // --------------------------------------

}