This is my text file named read.txt:
ID Name
22 Joe
33 Jim
ID Name
44 Bob
55 Jeff
ID Name
66 Mike
Task: Every time the code encounters the string "ID", it has to add the line after it into a list. So, for example:
(List1)
22 Joe
33 Jim
(List2)
44 Bob
55 Jeff
(List3)
66 Mike
Problem: I'm having trouble with reading the text file. I looked up other questions that have been asked on here and saw that cin.fail()
might be of use. So, I looked it up in my textbook and tried implementing it but the program just displays a blank screen when I compile. When I take out all the strings ID
and just have the numbers and names, the code works perfectly.
This is the section of my code:
int main()
{
ifstream file_read;
file_read.open("read.txt");
LinkedList list1, list2, list3, list4; //lists are of type linkedlist
string name, name2, name3;
int ID;
int counter = 0; //counter initialized
while (file_read.is_open()) { //run loop until end of file reached
if (file_read.fail()) { //when cin fails
counter++; //increment counter
if (counter == 1) { //if counter is 1
file_read >> ID >> name;
list1.Add(name, ID); //add following names to list1
}
if (counter == 2) { //if counter value is 2
file_read >> ID >> name2;
list2.Add(name2, ID); //add to list 2
}
if (counter == 3) { //if counter value is 3
file_read >> ID >> name3;
list3.Add(name3, ID); //add to list 3
}
}
}
file_read.close();
}
List 1,2,3 are linkedlists. Add is a function of linked list. These parts of the code work correcly, I am only having trouble with the text-file portion
Output: I'm getting a blank screen.
Could someone tell me what I'm doing wrong and how I can split the text file data into sections whenever I encounter a string? Thank you in advance.