问题
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();
}
回答1:
>>
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;
}
来源:https://stackoverflow.com/questions/26905427/c-getline-looping-when-used-in-file-with-a-read-in-int-array