Search code examples
c++filestructurestore

Extract data from text file in formatted/sequential way


I have a file .txt with this structure:

000010109000010309000010409

Where i need to read like this:

00001 01 09
00001 03 09
00001 04 09

I have a structure in this way:

struct A{
    string number // first 5 numbers
    int day; // 2 numbers
    int month; // last 2 numbers
};

I tried in this way. But dont work.

    char number[6];
    char day[3];
    char monthes[3];
    ifstream read("file.txt");
    for (int i = 0; i < 100; i++) {
        read.get(number,6);
        structure[i].number= number;
        read.get(day,3);
        structure[i].day= atoi(day);
        read.get(month,3);
        structure[i].month= atoi(month);
    }

How read and store the datas from the file to this structure? And how compare if the number have in the same month many days. Thanks a lot.


Solution

  • You could try something like this:

    FILE *fp = fopen("file.txt", "r");
    A a;
    char x[6], y[3], z[3];
    fscanf(fp, "%5s%2s%2s", x, y, z);
    a.number = string(x);
    a.day = atoi(y);
    a.month = atoi(z);
    

    EDIT:

    It is valid C++ code (with cstdio and cstdlib), but if you want some C++ version, you could try something like this

    // read from file.txt
    std::ifstream inFile("file.txt", std::ios::in);
    char number[6], day[3], month[3];
    int cnt = 0;
    while (inFile.get(number, 6) && inFile.get(day, 3) && inFile.get(month, 3)) {
        // Let's assume that structure[] is array of struct A
        structure[cnt].number = number;
        structure[cnt].day = atoi(day);
        structure[cnt].month = atoi(month);
        ++cnt;
    }
    // store to file2.txt
    std::ofstream outFile("file2.txt", std::ios::out);
    for (int i = 0; i < cnt; ++i) {
        outFile << structure[i].number << ' ' << structure[i].day << ' ' << structure[i].month << std::endl;
        // If you need fixed-width for day/month, use std::setw and std::setfill
    }
    // compare first two
    if (cnt >= 2) {
        if (structure[0].number == structure[1].number &&
            structure[0].month  == structure[1].month  &&
            structure[0].day    == structure[1].day) {
                std::cout << "Same!" << std::endl;
        } else {
            std::cout << "Different!" << std::endl;
        }
    }