c++ getline() looping when used in file with a read in int array? -
so posted other day not enough information , never got answer once added information asked, can't loop work question is, reading file has large text of strings on each line, has ints on next line strings need read questionarrays() , ints answersarrays.
currently loop goes round once , loops doesn't further in file on next getline() did have working without reading of ints part assume breaks it. file ordered in order of string int string int , on, if there way of splitting these read in accepted answer.
ifstream questionfile; int = 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(); }
>>
consume number, not remainder of line (including end-of-line marker). next getline
read empty line, , next >>
fail, putting stream bad state don't check for. loop forever, reading nothing , never reaching end of file.
you need to:
- ignore remainder of answer line
- check failure
- check end-of-file after reading, not before.
a better loop structure might 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 error somehow } ++i; }
Comments
Post a Comment