I am doing a textbook exercise that requires scoring student tests.
The input file looks like:
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF
The first line is the answer key for a test, and the following lines are student IDs and their responses, with blanks as an unanswered question.
The very first thing I need to do is read the first line so that I have something to compare the responses to. My first thought is to use a character array, but I can't seem to get it right. The first method I tried is:
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
const int NUM_QUESTIONS = 20;
using namespace std;
int main() {
// Vars
char answers[NUM_QUESTIONS];
ifstream infile;
// Open File
infile.open("Ch8_Ex6Data.txt");
infile.getline(answers, NUM_QUESTIONS);
cout << answers << endl;
infile.getline(answers, NUM_QUESTIONS);
cout << answers << endl;
return 0;
}
Which outputs
TTFTFTTTFTFTFFTTFTT
This is the all of the answers, but I noticed I couldn't do this twice to get to the next line. The second getline() sees an empty string.
The second method I tried was:
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
const int NUM_QUESTIONS = 20;
using namespace std;
int main() {
// Vars
char answers[NUM_QUESTIONS];
ifstream infile;
// Open File
infile.open("Ch8_Ex6Data.txt");
// Read first line into character array
infile.getline(answers, '\n');
cout << answers;
return 0;
}
Which outputs:
TTFTFTTTF
Which clearly isn't the whole line.
What should I do from here?
getlinereadsNUM_QUESTIONSchars and keeps\n, an empty line for nextgetline, call it with a single std::string argument.infile.getline(answers, '\n');is invalid, that overload is forstd::string, but you actually call it with the arrayinfile.getline(answers, 10);, thus you get 10 chars.std::stringif only to avoid the endless misery that is C strings.std::stringis and how it works. It'll make this program much, much easier.