Do-While loop LOOPS forever

I have a text file (schedule.txt) that has data that looks like this:
Monday, Physics 101, Calc 27, Chem 130
Tuesday, English 100, CompSci 87, Arts 147
Wednesday, Comm 58, Econ 96


Now I want to read each string from file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct classes
{
  string Day;
  string className;
  vector<string> vecClassName;
}
classes myClasses;
ifstream inputFile;
inputFile.open("schedule.txt");
while (!eof())
{
  getline(inputFile, myClasses.Day, ',');
  do{
    getline(inputFile, myClasses.className, ',');
    myClasses.vecClassName.push_back(myClasses.className);

   }while (myClasses.className != "\n"); // Get all classes until end of line

 // other code here --
// Compiler doesn't reach this point - the do-while loop Loops forever nonstop.

}

I don't understand why the do-while Loops forever I want it to stop until there are no classes in that line
Please Help me fix this!
Last edited on
I'm no expert so I'm just guessing here, but perhaps it has to do with your struct? The same classes object that holds the string for one particular class also holds the vector of all the class names, so maybe your code is getting caught in the push_back() line. Have you tried commenting anything out to see what causes the endless loop?
The do-while loop loops forever because you don't check if the end of the file is reached in the do-while loop so you should check the state of the stream.
simply add a && inputFile to the while statement to accomplish that:
while (myClasses.className != "\n" && inputFile);

getline emmits the delimiter (default value for the delimiter is '\n')
so when calling getline with ',' getline reads the parts between two ','

In your example the last element of the first line and the first element of the second line are seperated by a newline but not by a comma so they won't be splitted.

The string you want to split looks like this:
{last_old_line_element + '\n' + first_new_line_element}

I think I just gave you a very good hint so good luck! ;)
Last edited on
@ Gamer2015
Thanks for the hint! It works !!!
Topic archived. No new replies allowed.