首页 > 解决方案 > C++ 仅从输入文件中读取一些(不是全部)数据以添加到记录中

问题描述

我目前有一个包含如下数据的 CSV 文件:

名字...头发...鸡蛋...高...水...土地...国内

应用.......1............0............1............0............0.. ............1

大坝......1............1............0............0............1...... .........1

亿万年......0............1............0............1............1...... ..........0

其中 0 为假,1 为真。我只对阅读对象 Name、Tall 和 Domestic 感兴趣,我将把它们添加到记录中。到目前为止我有

    ifstream inFile("file_name.csv");

    if (inFile.fail())
    {
        std::cout << "File cannot be opened due to an error." << endl;
        exit(1);
    }

  string junk;
  getline(inFile,junk);

我对如何设置 while 循环以跳过不必要的数据持空白。这样做是没有意义的 while(inFile >> name >> hair >> eggs >> tall >> water >> land >> domestic)我正在考虑 while 循环中的 for 循环,但我只是可以不要在我的脑海中解决它。任何帮助/指导将不胜感激。

附上表图片

标签: c++fstreamgetline

解决方案


在这些情况下,我建议您使用类或结构对每一行进行建模:

struct Record
{
    std::string name;
    int hair;
    int eggs;
    int tall;
    int water;
    int land;
    int domestic;
    friend std::istream& operator>>(std::istream& input, Record& r);
};

std::istream& operator>>(std::istream& input, Record& r)
{
    input >> name;
    input >> hair;
    /...
    input >> domestic;
    return input;
}

通过重载operator>>,您可以简化输入:

std::vector<Record>  database;
Record r;
while (data_file >> r)
{
    database.push_back(r);
}

要访问该Name字段:

std::cout << database[3].name << "\n";

推荐阅读