I have to write a program helps your instructor grade quizzes. The program will read a file containing a single student’s answers to a recently given quiz. It will compute the student’s grade on the test as a percentage, and then print a report Your program should read the file answers.dat. This file contains the name of the student who took the quiz, and his answers for each question. The answers file has the following format: The student name is always the first line. A student name may or may not have last names. A quiz always has 11 questions. There is one answer per line. Each answer is one word and all lowercase.
Reading a whole line (needed for student names) from an ifstream and 11 answers:
1 2 3
std::string str;
ifst.get_line( str); // reads a whole line into a string
for (int i = 0; i <11; ++i) { ifs >> given_answers[i]; }
Also I would use std::vector instead of raw arrays:
1 2
std::vector<std::string> given_answers(11); // initialises an 'array' of size 11 empty strings
for(auto str : given_answers) std::cout << str << '\n'; // Example use of such vector
Read in the answers.dat:
1 2 3 4 5 6 7
std::vector<std::string> correct_answers; // An empty vector
std::ifstream ifstr_corr_answ("answers.dat"); // Opens the ifstream
if (!ifstr_corr_answ) return;
while (ifstr_corr_answ) { // reads until the stream is empty
ifstr_corr_answ >> std::string str;
correct_answers.push_back( str ); // adds the new string at end of its array
}
How to operate on such vector:
1 2 3 4 5 6 7 8 9
// passing the args as references (!)
int get_correct_answers(const std::vector<std::string>& answers, const std::vector<std::string>& solutions)
{
if solutions.size() < answers.size() return -1; // vectors shouldn't have different sizes
int count = 0;
for ( int i = 0; i < solutions.size(); ++i) {
if (solutions[i] == answers[i]) ++count;
}
return count;
Look at cppreference.com for right use of std::vector. That's an often used type (beside string).