首页 > 解决方案 > 从一个文件 c++ 中读取不同的变量类型

问题描述

我在将特定格式的数据读入不同的变量时遇到了一些麻烦。我需要从文件中读取数据并存储到 5 个不同变量类型的不同变量中。(字符串名称、字符串鱼、字符串位置、浮点长度、浮点重量)

我尝试存储的数据格式如下:

数据如何存储在文件中的图片

使用 getline() 函数从文件中获取名称、鱼和位置没有问题。我的问题是长度和宽度。

ifstream file("test.txt");

while(file.good())
{
    getline(file, Name);
    getline(file, Species);
    getline(file, Location);
    file >> Length;
    file >> Weight;

    cout << Name << "\n" << Species << "\n" <<Location << "\n" <<Length << "\n";

}

当我使用以下代码时,输​​出会变得不稳定,并且在第一次列出之后会乱序打印数据。对此的任何帮助将不胜感激。

标签: c++

解决方案


ifstream file("test.txt");
while (file) {
    getline(file, Name);
    getline(file, Species);
    getline(file, Location);
    file >> Length;
    file >> Weight;

    if (file) {
       cout << Name << "\n" << Species << "\n" <<Location << "\n" <<Length << "\n";

        // add this to skip the 2 newlines before reading the next string
        file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    }
    else {
       throw "Invalid input";
    }
}

推荐阅读