Reading an array from a text file and storing it using Classes and constructors.

Hello everyone. I have a an array in a file i-e 1 2 3 4 . each of these numbers are of different attributes. Can anyone tell me the way how to store them using classes and constructors?

file.txt:
1 2 3 4

Put each number into the into the Foo class's member variables (AKA attributes):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <fstream>
#include <iostream>

class Foo {
    
  public:
    int fab;
    int fob;
    int fib;
    int fub;
    
};

int main()
{
    std::ifstream fin("file.txt");
    if (!fin)
    {
        std::cout << "Error opening file.txt" << std::endl;
        return 1;
    }
    
    Foo bar;

    // Attempt to read in each number, delimited by whitespace
    if (fin >> bar.fab >> bar.fob >> bar.fib >> bar.fub)
    {
        std::cout << "Successfully read file " << std::endl;
        std::cout << bar.fab << " "
                  << bar.fob << " "
                  << bar.fib << " "
                  << bar.fub << std::endl;
    }
    else
    {
        std::cout << "Failed to parse file" << std::endl;
        return 2;
    }
    
    return 0;
}
Last edited on
Registered users can post here. Sign in or register to post.