c++ - 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 循环,但我只是可以不要在我的脑海中解决它。任何帮助/指导将不胜感激。
解决方案
在这些情况下,我建议您使用类或结构对每一行进行建模:
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";
推荐阅读
- c - 为什么我的代码在 Visual Studio 中完美运行,但在 gcc 编译器上出现分段错误
- c# - 我正在尝试在每次点击 itextsharp 时将内容添加到表格中
- c++ - Eclipse CDT 项目中的默认 C++ 标准是什么?
- api - 从文件夹下载的文件包括 .NET Core 上的 %2F 字符
- ios - 完全加载时如何关闭progressView?
- c - 我的 c 代码中的本地布尔代码有错误
- mysql - Keycloak 使用现有 MySQL 数据库进行用户身份验证的用户联合
- python - 如何在 matplotlib 中创建径向热图?
- javascript - 多个验证函数被视为 OR 而不是 AND
- php - 我的联系公式以前工作过 - 现在不行 - php