Program creating new object depending on input?

Disclaimer: I am new to c++ and programming in general so I apologize if my question doesn't make sense.
Ok so I am wondering if there is a way for a program to make its own objects based on the inputs given, more specifically if they are for a class. For example, I am opening and trying to transfer data from a text document into the program to be recorded. For this I made a class that has a constructor function that gets int userNum1, int userNum2, float amount, and string reason, when called in main(). The thing is that there is no specific number of how many objects will be recorded because the text file can be edited (add or remove data in it). I want all the data present in the file to be recorded as an object but don't know how many objects will be needed. So is there a way to create a new object as long as there is information available that is distinguished and can be later accessed. For example after getting the values for the variables userNum1, userNum2, etc., it stores the values into object pay1 and the next set of values stored into pay2, then pay3, etc (with the only difference in name being the different number). I hope this makes sense, thank you for your time.
Last edited on
Use a vector of objects. vector: https://cal-linux.com/tutorials/vectors.html

For example:
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
42
43
44
45
46
47
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

struct payment
{
    payment( int n, double amt, const std::string& rsn ) : number(n), amount(amt), reason(rsn) {}

    int number ;
    double amount ;
    std::string reason ;
};

// create a vector (a collection) of payment objects from an input stream (this may be a file stream)
std::vector<payment> get_payments( std::istream& stm )
{
    std::vector<payment> all_payments ;

    int n ;
    double amt ;
    std::string rsn ;

    // for each tuple n,amt,rsn read from the stream,
    // (read n, read amt, discard white space, read the rest of the line into rsn)
    // the loop ends when input fails (eg. there is nothing more to read)
    while( stm >> n >> amt >> std::ws && std::getline(stm,rsn) )
    {
        // add another payment object to all_payments vector
        all_payments.emplace_back( n, amt, rsn ) ;
    }

    return all_payments ;
}

int main()
{
    std::ifstream file( "payments.txt" ) ; // open a file for input
    std::vector<payment> all_payments = get_payments(file) ; // read in all the payments in the file

    for( const payment& p : all_payments ) // for each payment p in the vector
    {
        // do something with p
    }

    // the payments can also be accessed as all_payments[0], all_payments[1] etc.
}
Topic archived. No new replies allowed.