无法读取文本文件

Having trouble reading text file

这是我的文本文件 read.txt:

ID Name
22 Joe
33 Jim
ID Name
44 Bob
55 Jeff
ID Name
66 Mike

任务: 每次代码遇到字符串 "ID" 时,它都必须将其后的行添加到列表中。所以,例如:

(List1)
22 Joe
33 Jim

(List2)
44 Bob
55 Jeff

(List3)
66 Mike

问题: 我在读取文本文件时遇到问题。我查看了此处提出的其他问题,发现 cin.fail() 可能有用。因此,我在我的教科书中查找并尝试实现它,但程序在我编译时只显示一个空白屏幕。当我取出所有字符串 ID 并且只有数字和名称时,代码可以完美运行。

这是我的代码部分:

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();
}

列表 1、2、3 是链表。添加是链表的功能。代码的这些部分工作正常,我只有文本文件部分有问题

输出:我得到一个空白屏幕。

谁能告诉我哪里做错了,以及当我遇到字符串时如何将文本文件数据拆分成多个部分?提前谢谢你。

你的意思可能是

if (! file_read.fail()) {

而不是if (file_read.fail())?毕竟,如果读取成功,您只想添加到列表中。