this creates an empty vector vector <int> gradeVector;
This writes into the Input'th element of the empty vector, which doesn't actually exist, so it writes to some other variable's memory, or maybe over your function's return address, memory you don't own, etc. gradesDoc >> gradeVector [Input];
To append a value to the vector, us push_back (and, while at it, stop using .eof())
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <fstream>
#include <vector>
usingnamespace std;
int main()
{
ifstream gradesDoc ("/Users/DPRiddle/Documents/School 2013/C++/Grades.txt");
vector <int> gradeVector;
double runnTotal=0;
int value;
while (gradesDoc >> value)
{
gradeVector.push_back(value);
runnTotal += value;
}
cout << "The average grade was:" << runnTotal/gradeVector.size()<< '\n';
}
Before you can access a vector element with the array notation[] the element must already exist. You may want to look a the documentation for vector and look at the vector.push_back() member function.
ah. thanks. that works. cubbi: why stop using .eof?
and while your answering questions: the only way i could get the program to find the .txt file was to put in the file path, but i rarely see file path in sample code of this nature. is there someplace i can put the document that the compiler will look for it automatically?
Because it's an error to use it that way, for two reasons: First, it doesn't predict the future: it's still false at the end of file, it's only true after you attempted, and failed, to read past the end. Second, if you have a non-digit in the file, the input operation will fail with syntax error, and you will find yourself in an endless loop.
is there someplace i can put the document that the compiler will look for it automatically?
In the current working directory of your program. Where it is depends on the manner in which you're running your program (for a notorious example, Visual Studio uses different paths for debug and release builds). Mac is a unix environment, so the normal usage would be to put your program in directory listed in PATH, open a shell window, nagivate to the data file, and run the program (which would be found in PATH) while in that directory.