无法读取完整文件c ++

时间:2018-02-14 15:02:48

标签: c++ c++11

我正在尝试使用文件中的生物填充链接列表。但是,当我这样做时,它会读取第一个但没有其他生物。我无法传递一个int来获取生物数量,因为它不是静态的。

我有以下代码

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

void clearBuffer() {
    cin.clear();
    cin.ignore(100, '\n');
}

void enterMagicalCreatureFromFile() {
    string filepath = "test.txt";
    ifstream creatureFile;
    creatureFile.open(filepath);
    if (!creatureFile) {
        cerr << "Unable to open file " << filepath << endl;
        return;
    }
    string name, description;
    float cost;
    char danger;
    int numCreated = 0;
    while (getline(creatureFile, name) && getline(creatureFile, description) && creatureFile >> danger && creatureFile >> cost) {
        cout << "name: " << name << " desc: " << description << " danger: " << danger << " cost: " << cost << endl;
        numCreated++;
    }
    cout << numCreated << " creatures from " << filepath << " have been added to the zoo" << endl;
}

int main() {
    enterMagicalCreatureFromFile();
}

文件test.txt看起来像

Beholder
Giant center eye and twelve eye stalks above it.  It is a flying eyeball.  Mouth full of razor sharp teeth.  Eye stalks shoot various beams of magical death-dealing energy.
1
750.85
Banshee
The English Banshee is a fairy woman who wails when death is approaching.They do not cause death, only mourn it.  Banshees are almost always female, and are usually seen with long, dark, black hair and pale chees.  Their eyes also are usually red from crying.
0
15.5
Troll
Ugly and big.  Sometimes smell bad.
1
85648.34
Mike Wazowski
One-eyed, funny green monster.  A scare assistant to James P. Sullivan at Monsters, Inc.  Mike doesn't want any interruptions in his life.
0
455.32
Unicorn
The unicorn is a legendary creature that has been described since antiquity as a beast with a single large, pointed, spiraling horn projecting from its forehead. 
0
24.32
Sasquatch
The sasquatch is also called Big Food.  Bigfoot is a cryptid in American folklore, supposedly a simian-like creature that inhabits forests, especially those of the Pacific Northwest. Bigfoot is usually described as a large, hairy, bipedal humanoid.
1
39475.93

正如我所说,第一个生物“Beholder”加载并完全添加到列表中,所以我认为我的逻辑不在列表或生物文件中。

我被困了,有什么指针吗?

1 个答案:

答案 0 :(得分:0)

阅读双cost后,在creatureFile信息流中等待换行。

在阅读下一个生物之前,我们需要使用ignore()超越它:

while (std::getline(creatureFile, name)
       && std::getline(creatureFile, description)
       && creatureFile >> danger
       && creatureFile >> cost)
{
    std::cout << "name: " << name
              << " desc: " << description
              << " danger: " << danger
              << " cost: " << cost
              << std::endl;
    ++numCreated;
    creatureFile.ignore(100, '\n');
}