I'm having trouble reading in data from a plain-text file using the ifstream object.

I am using Microsoft Visual Studio 2013. I have read the page from the CPlusPlus.com tutorial involving file I/O ("Input/output with files") several times, but I still cannot get my code to work. I am feeding the input the correct name of a valid plain-text file which is located in the local directory (the same directory as the *.exe file) but the file always fails to open. I set a breakpoint on line 193 and 196 to try and figure out what the problem was. The ifstream object, called "myfile", shows "Error reading characters of string." in the Locals window and myfile.is_open() evaluates to false. I've also tried invoking the c_str() member function of the fileName string when passing my parameters to the ifstream object's constructor.

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

class Student
{
    public:

        Student(const string newName)
        {
            const vector<string> nameParts = splitString(newName, ' ');

            this->setName(newName);
            this->setLastName(nameParts.at(0));
            this->setFirstName(nameParts.at(1));
            this->setMiddleInitial(nameParts.at(2)[0]);
            this->setDataFileName(this->getFirstName() + this->getLastName() + ".dat");

            if (!this->readScoresFromDataFile())
            {
                cerr << "ERROR: Unable to open student data file." << endl;
            }
        }

        const double            getAvgScore()       { return this->avgScore; }
        const string            getDataFileName()   { return this->dataFileName; }
        const string            getFirstName()      { return this->firstName; }
        const string            getLastName()       { return this->lastName; }
        const double            getMaxScore()       { return this->maxScore; }
        const char              getMiddleInitial()  { return this->middleInitial; }
        const double            getMinScore()       { return this->minScore; }
        const string            getName()           { return this->name; }
        const vector<double>    getScores()         { return this->scores; }

        void setAvgScore(const double newAvgScore)          { this->avgScore = newAvgScore; }
        void setDataFileName(const string newDataFileName)  { this->dataFileName = newDataFileName; }
        void setFirstName(const string newFirstName)        { this->firstName = newFirstName; }
        void setLastName(const string newLastName)          { this->lastName = newLastName; }
        void setMaxScore(const double newMaxScore)          { this->maxScore = newMaxScore; }
        void setMiddleInitial(const char newMiddleInitial)  { this->middleInitial = newMiddleInitial; }
        void setMinScore(const double newMinScore)          { this->minScore = newMinScore; }
        void setName(const string newName)                  { this->name = newName; }
        void setScores(const vector<double> newScores)      { this->scores = newScores; }

    protected:

        bool readScoresFromDataFile(void)
        {
            string line = "";
            vector<double> studentScores = this->getScores();

            ifstream myfile(this->getDataFileName());

            if (myfile.is_open())
            {
                double average = 0, maximum = 0, minimum = 0, score = 0;
                bool firstLoopExecution = true;

                while (getline(myfile, line))
                {
                    score = stod(line);
                    studentScores.push_back(score);
                    average += score;

                    if (firstLoopExecution)
                    {
                        minimum = score;
                        maximum = score;
                        firstLoopExecution = false;
                    }

                    if (score < minimum)
                    {
                        minimum = score;
                    }

                    if (score > maximum)
                    {
                        maximum = score;
                    }
                }

                myfile.close();

                average = average / ((double)studentScores.size());

                this->setMaxScore(average);
                this->setMaxScore(maximum);
                this->setMinScore(minimum);
                this->setScores(studentScores);
            }
            else
            {
                return false;
            }

            return true;
        }

        static const vector<string> splitString(const string &s, char delim, bool ignoreEmptyStrings = true)
        {
            stringstream ss(s);
            vector<string> elems;
            string item = "";

            while (getline(ss, item, delim))
            {
                if (ignoreEmptyStrings)
                {
                    if (!item.empty())
                    {
                        elems.push_back(item);
                    }
                }
                else
                {
                    elems.push_back(item);
                }
            }

            return elems;
        }

    private:

        double avgScore = 0;
        string dataFileName = "";
        string firstName = "";
        string lastName = "";
        double maxScore = 0;
        char middleInitial = 0;
        double minScore = 0;
        string name = "";
        vector<double> scores;
};

int main(int argc, char *argv[])
{
    string line = "", fileName = "";
    vector<Student> students;

    cout << "Enter Name of Data File: ";
    cin >> fileName;
    cout << endl;

    ifstream myfile(fileName, ios_base::in);

    if (myfile.is_open())
    {
        while (getline(myfile, line))
        {
            Student myStudent(line);
            students.push_back(myStudent);
        }

        myfile.close();

        double classAverage = 0, classMinimum = 0, classMaximum = 0;
        bool firstLoopExecution = true;

        cout << fixed << setw(20) << "Student" << "Average" << endl;

        for (Student student : students)
        {
            if (firstLoopExecution)
            {
                classMinimum = student.getMinScore();
                classMaximum = student.getMaxScore();
                firstLoopExecution = false;
            }

            if (student.getMinScore() < classMinimum)
            {
                classMinimum = student.getMinScore();
            }

            if (student.getMaxScore() > classMaximum)
            {
                classMaximum = student.getMaxScore();
            }

            classAverage += student.getAvgScore();

            cout << fixed << setw(20) << setprecision(2) << student.getFirstName() + student.getMiddleInitial() + student.getLastName() << student.getAvgScore() << endl;
        }

        classAverage = classAverage / ((double)students.size());

        cout << endl;
        cout << fixed << setw(20) << setprecision(2) << "Class Average:" << classAverage << endl;
        cout << fixed << setw(20) << setprecision(2) << "Class Maximum:" << classMaximum << endl;
        cout << fixed << setw(20) << setprecision(2) << "Class Minimum:" << classMinimum << endl;
    }
    else
    {
        cerr << "ERROR: Unable to open class data file." << endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
Last edited on
In the debug environment the default/current path is not necessarily where the exe is. It is where the project files are.

Try for debugging purposes an absolute path.

Alternatively you can change the default path in your project settings.
Thank you very much! Moving my data files and then re-running the program until I found the correct directory where my environment expected to find them solved the problem.
Topic archived. No new replies allowed.