我目前有一个CSV文件,其数据如下:
名称...头发...鸡蛋...高...水...土地...国内
Appl ....... 1 ......... 0 ........ 1 ........ 0 .......... 0 ............. 1
Dams ..... 1 ......... 1 ........ 0 ........ 0 .......... 1 .. ........... 1
Eons ...... 0 ......... 1 ........ 0 ........ 1 .......... 1。 ............ 0
其中0为假,1为真。我只想读名称,高和国内对象,我将其添加到记录中。到目前为止,我有
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循环以跳过不必要的数据方面空白。只是没有意义而已(inFile >>名称>>头发>>鸡蛋>>高>>水>>土地>>国内),我想在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";