Print Vector from Class

Hello,
I am trying to read a data file into a vector and print the values through class. When compiled there are no errors, but the program just stops after opening the file. Can't seem to figure out the problem. Any help is appreciated. Thank you.

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
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <vector>
#include <cmath>
using namespace std;

class circuit
{
    public:
        void openfile()
        {
            cout << "Enter input file name for time values: ";
            cin >> filename;
            infile.open(filename.c_str());
            while(infile.fail())
                {
                    cout << "Invalid file name." << endl;
                    cout << "Reenter file name: ";
                    cin >> filename;
                    infile.open(filename.c_str());
                }
        }

        void readfile()
        {
            while(infile >> t)
            {
                for (int i = 0; i < time.size(); i++)
                {
                    time.push_back(t);
                }
            }
        }
        
        void print()
        {
            for(vector<double>::iterator i = time.begin(); i != time.end(); ++i) 
            {
                cout << *i << endl;
            }
        }

    private:
        string filename;
        ifstream infile;
        double t;
        vector<double> time;
        vector<double> Vout;
};

int main()
{
    circuit project;
    project.openfile();
    project.readfile();
    project.print();
    return 0;
}
Last edited on
put a cout << t << endl; on line 34 so it proves you opened the file, got data, and put something into that vector. if that prints the file contents correctly, we can look deeper.

my personal guess is that the above does not work because time() is empty so time.size() is 0
Last edited on
oh okay when adding that line, it doesn't even read the file
did you see what I said? I suspect time.size() is zero.... do you ever populate this vector, or if not, are you looping over totally the wrong thing?
1
2
3
4
5
6
7
void readfile() {
            while(infile >> t) {
                for (int i = 0; i < time.size(); i++) {
                    time.push_back(t);
                }
            }
        }


I'm not sure what you're trying to accomplish here, but nothing will ever be added to time. At the start, time.size() is 0, i is 0 which is not < 0 so .push_back() will never be executed!

Perhaps (not tried) ?

1
2
3
void readfile() {
    for (double t {}; infile >> t; time.push_back(t));
}


Also for print():

1
2
3
4
void print() {
    for (const auto& t : time)
        cout << t << '\n';
}

Topic archived. No new replies allowed.