1

だから私はこのファイルを読み込もうとしています。すべてが機能するように見えますが、実行時にプログラムがタイムアウトして機能を停止するため、プログラムを閉じる必要があります。何が起こっている?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

助言がありますか?

4

2 に答える 2

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;
        }
    }
}
于 2010-10-01T18:27:15.240 に答える
0

それが機能していないということはどういう意味ですか? この書き方では、予想よりも 1 行多く読み取ろうとします。

これは、最後の行が読み取られたときに getline がまだヒットしていないためですが、行eofを読み取ろうとすると、最後の行の後にヒットするためeofです。だから、これはあなたの問題かもしれません。

于 2010-10-01T20:36:58.113 に答える