C++ eof() problem - never returns true?

前端 未结 2 1397
盖世英雄少女心
盖世英雄少女心 2021-01-24 11:46

So I\'m trying to read this file. Everything looks like it should work, but during runtime the program times out and stops working, and I have to close it. What is going on? I s

2条回答
  •  终归单人心
    2021-01-24 12:12

    eof returns true after you tried to read something and the operation failed. So put it after getline.

    EDIT: try this code:

    vector petArray;
    ifstream textFile2("pets.txt");
    
    string temp;
    int tmpNum = 0;
    
    while (getline(textFile2, temp))
    {
        if (temp == "Dogs") tmpNum = 0;
        else if (temp == "Cats") tmpNum = 1;
        else if (temp == "Iguanas") tmpNum = 2;
        else if (temp == "Pigs") tmpNum = 3;
        else
        {
            if (tmpNum == 0)
            {
                petArray.push_back(new Dog(temp));
                cout << "Dog " << temp << " added" << endl;
            }
            if (tmpNum == 1)
            {
                petArray.push_back(new Cat(temp));
                cout << "Cat " << temp << " added" << endl;
            }
            if (tmpNum == 2)
            {
                petArray.push_back(new Iguana(temp));
                cout << "Iguana " << temp << " added" << endl;
            }
            if (tmpNum == 3)
            {
                petArray.push_back(new Pig(temp));
                cout << "Pig " << temp << " added" << endl;
            }
        }
    }
    

提交回复
热议问题