When I want to access a part of the vector (appointment) it won't allow it, for example simply adding: cout << appointment[1];
won't work.
I also want this vector to be saved to my class (Appointment), so I can later remove elements of the vector. Would I be able to do this simply by declaring the vector in the class? i.e.
class Appointment
{
private:
vector <string> appointment;
}
This is my whole code:
void Appointment::loadAppointments()
{
ifstream Appointments;
string line;
vector <string> appointment;
int i = 1;
cout << "You have the following appointments:" << endl;
开发者_JAVA百科
Appointments.open(DATAFILE);
if (Appointments.is_open())
{
while (!Appointments.eof())
{
getline(Appointments, line, '\n');
appointment.push_back(line);
}
Appointments.close();
}
cout << "this is a test" << appointment[1] << endl;//This part will not function
}`
You are re-declaring vector appointment twice in your code; once as a member variable and once as a local variable in your loadAppointments function. Remove the declaration in your function and you should be good to go.
Rather than checking for EOF, change your input loop to look like the following:
Appointments.open(DATAFILE);
getline(Appointments, line);
while(Appointments.good())
{
appointment.push_back(line);
getline(Appointments, line);
}
//a debug statement to check the number of records read
cout << "Number Appointments: " << appointment.size() << endl;
This will check for any errors that might have occurred during the reading of the file rather than just looking for EOF. Additionally you will avoid a double-read at the end of the file because of the way you're reading in lines from the file (i.e., a call to getline
may trigger the EOF flag, but you will still push the line
string from the call to getline
into your vector).
Secondly yes, make the vector appointment
a private non-static data-member if you want that information saved with the object. If you do that, there is no need to declare it as an automatic variable in the function itself. Keep in mind though, if you decide to make this change, that each time you call loadAppointments
, you may want to empty out the vector, otherwise you will simply be appending new information onto possibly old/out-dated information, since the lifetime of the vector now outlives the function itself and instead is tied to the lifetime of the Appointment
object.
The first element of your vector is appointments[0]
, not appointments[1]
. In C++, vector elements are numbered starting at 0. If you've only got one entry in your appointments file, then this could be the cause of your difficulty.
精彩评论