0

So I posted this the other day with not enough information and never got an answer once I added the information asked, so I can't get the loop to work so my question is, I am reading from a file that has large text of strings on each line, it then has ints on the next line the strings need to be read into questionArrays() and the ints into answersArrays.

Currently the loop simply goes round once and then just loops as it doesn't get any further in the file on the next getline() I did have this working without the reading of ints part so I assume this is what breaks it. The file is also currently ordered in order of string then int then string then int and so on, if there is a way of splitting these up to read in that would also be an accepted answer.

ifstream questionFile;
int i = 0;
switch (x){
case 1:
    questionFile.open("Topic1 Questions.txt", ios::app);
    break;
case 2:
    questionFile.open("Topic2 Questions.txt", ios::app);
    break;
case 3:
    questionFile.open("Topic3 Questions.txt", ios::app);
    break;
case 4:
    questionFile.open("Topic4 Questions.txt", ios::app);
    break;
}
if (!questionFile)
{
    cout << "Cannot load file" << endl;
}
else
{
    if (questionFile.peek() != ifstream::traits_type::eof()) {
        while (!questionFile.eof())
        {
            getline(questionFile, questionsArray[i]);
            questionFile >> answersArray[i];
            i++;
        }
    }
    questionFile.close();
}
bilbsy
  • 67
  • 1
  • 10
  • what are you trying to do with questionFile >> answersArray[i] ? – Pandrei Nov 13 '14 at 09:44
  • @Pandrei: Read an integer from the file into an array, as described. – Mike Seymour Nov 13 '14 at 09:44
  • I think this is more of a conceptual problem than anything else; I would split the problem into more approachable tasks: 1)read a line from file; 2) parse the line to see if it contains strings or ints – Pandrei Nov 13 '14 at 09:48

1 Answers1

3

>> will consume the number, but not the remainder of the line (including the end-of-line marker). So the next getline will read an empty line, and the next >> will fail, putting the stream into a bad state that you don't check for. It will then loop forever, reading nothing and never reaching the end of the file.

You need to:

  • ignore the remainder of the answer line
  • check for failure
  • check for end-of-file after reading, not before.

A better loop structure might look something like

while (getline(questionFile, questionsArray[i])) {
    if (questionFile >> answersArray[i]) {
        questionFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } else {
        throw std::runtime_error("Missing answer"); // or handle the error somehow
    }
    ++i;
}
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644