#include <iostream>
#include <fstream>
#include <vector>
usingnamespace std;
int main()
{
std::ifstream f("grade.txt");
vector<int> grades;
int grade = -1;
while (f >> grade)
{
grades.push_back(grade);
}
int total = 0;
for(int i = 0; i < grades.size(); ++i)
{
total += grades[i];
}
cout << "The total grade is " << total << endl;
cout << "And the average grade is " << total/grades.size() << endl;
}
The first mistake is you forgot to include <vector>, but you use it.
Second is that you forgot to write the main() function...everything else, except you missing ";" in this line
int main()
{
std::ifstream f("grade.txt");
if (!f.is_open())
{
std::cout << "Error: failed to open file.\n";
return 1;
}
//the rest...
}
Is this your first time trying to work with a file?
possible solutions:
* Make sure your file is in the same directory as your executable (or if you're using an IDE that does things differently, wherever the IDE reads resources from).
* Depending on your OS, make sure another program using your file isn't preventing your program from accessing it.
grades.size() is 0 at this point, thus you're trying to divide by 0.
Learning how to figure out what compiler errors mean can be very useful.
14 16 test.cpp [Error] redeclaration of 'std::ifstream f'
You have the line std::ifstream f("grade.txt"); twice in your code, remove the second time you declare it. Hope it can compile now, and it should display an error if it can't open your file correctly.
The C++ part of you issue seems to be working fine now, there's something weird with what you're doing in your Windows OS or cmd, so I can't really help you there. What steps are you taking to run your executable, and what windows OS are you on?
I would try enter part of
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.
into a google search or something to try to find some relevant info, I have never had a problem like that using cmd so I probably can't help further.
Also, for next time you should use code tags for code posting, the [<>] button under Format.
Edit: If you can't get it to work, a temporary fix (don't do this in good code, as it makes it non-portable) would be to give the absolute path to your file
ex: std::fstream f("C:/programming/files/grade.txt");