I am working through Accelerated C++ and am on exercise 3-5. The question is:
Write a program that will keep track of grades for several students at once. The program could keep two vectors in sync: The first should hold the student's names, and the second the final grades that can be computed as input is read. For now, you should assume a fixed number of homework grades.
...so I made the following program:
#include <iostream>
#include <string>
#include <vector>
int main() {
// Enter students first names, separated with a space and ending in Enter+Ctrl+D (end-of-file)
std::cout << "Please enter the students names: ";
std::string name;
std::vector<std::string> students;
while (std::cin >> name) {
students.push_back(name);
}
// Enter the grads in batches of 5 e.g. for two students write 10 3 4 5 6 10 6 8 9 10 and ending in end-of-file
std::cout << "Please enter the students grades: ";
std::vector<int> grades;
int grade;
int count = 0;
int total = 0;
while (std::cin >> grade) {
if (count <= 4) {
total += grade;
++count;
} else {
grades.push_back((total / 5));
count = total = 0;
}
}
for (std::vector<std::string>::size_type i = 0; i < students.size(); i++) {
std::cout << students[i] << " scored " << grades[i] << std::endl;
}
return 0;
}
...except when I run it on OpenBSD I get a segmentation fault. When compiling the app with GCC I only get the recommendation:
/usr/lib/libstdc++.so.49.0: warning: strcpy() is almost always misused, please use strlcpy()
. I know from wikipedia that a segmentation fault is the program trying to access memory it shouldn't but I can't see where the seg(fault) lies.
I'd be grateful if a more experienced C++ programmer could point me in the right direction. Thanks in advance for any help/tips/pointers :)