C ++ eof()问题 - 永远不会返回true?

时间:2010-10-01 18:25:15

标签: c++ eof

所以我正在尝试阅读这个文件。一切看起来应该可以工作,但在运行时程序超时并停止工作,我必须关闭它。到底是怎么回事?我怀疑oef()测试永远不会返回true并且它会继续在文件中查找更多内容。我没有在文本文件中拖动空行。我试过像疯了一样调试这个。我找不到任何错误,但它仍然拒绝工作。

Pet** petArray;

ifstream textFile2;
textFile2.open("pets.txt");

int i = 0;
string temp;
int tmpNum = 0;

if (textFile2.is_open())
{
    while (!textFile2.eof())
    {

        getline(textFile2, temp);

        petArray = new Pet*[arraySize];

        if (temp == "Dogs" || temp == "Cats" || temp == "Iguanas" || temp == "Pigs")
        {
            if (temp == "Dogs") tmpNum = 0;
            if (temp == "Cats") tmpNum = 1;
            if (temp == "Iguanas") tmpNum = 2;
            if (temp == "Pigs") tmpNum = 3;
            temp == "";
        }
        else
        {
            if (tmpNum == 0)
            {
                petArray[i] = new Dog(temp);
                cout << "Dog " << temp << " added" << endl;
            }
            if (tmpNum == 1)
            {
                petArray[i] = new Cat(temp);
                cout << "Cat " << temp << " added" << endl;
            }
            if (tmpNum == 2)
            {
                petArray[i] = new Iguana(temp);
                cout << "Iguana " << temp << " added" << endl;
            }
            if (tmpNum == 3)
            {
                petArray[i] = new Pig(temp);
                cout << "Pig " << temp << " added" << endl;
            }
            arraySize++;
        }

        i++;
    }
}

以下是文本文件的格式:

Dogs
d1
d2
Cats
c1
c2
Iguanas
i1
i2
Pigs
p1
p2

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

eof返回true 之后您尝试读取内容并且操作失败。所以把它放在getline之后。

编辑:试试这段代码:

vector<Pet*> 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;
        }
    }
}

答案 1 :(得分:0)

你的意思是它不起作用?这样写的方式,这将尝试比你期望的更多地阅读一行。

这是因为,当读取最后一行时,getline还没有被eof点击,但是当尝试读取该行时,在最后一行之后,则会点击eof。所以,这可能是你的问题。