读取以逗号分隔的.txt文件并放入数组

时间:2019-10-09 18:16:27

标签: c++ arrays

说有一个名为“ dogs.txt”的文件,它具有名称,品种,年龄和编号。所以我想将每个元素读入我的C ++程序,以便可以通过dog [0,2]进行访问,这将给我第0个狗的第二个元素(品种)。

示例:

max, beagle, 12, 1  
sam, pit bull, 2, 2  

如何将其编码到程序中,然后将其存储到数组中?

我只能使用<iostream>, <fstream>, <iomanip>, <vector>, <cmath>, <ctime>, <cstdlib>,<string>

1 个答案:

答案 0 :(得分:0)

看起来您的输入数据是每行(行)一个记录
因此,让我们对行进行建模:

struct Record  
{
    std::string name;
    std::string breed;
    int         age;
    int         id;
    friend std::istream& operator>>(std::istream& input, Record& r);
};

std::istream& operator>>(std::istream& input, Record& r)
{
    // read the fields into a string.
    std::string text_line;
    std::getline(input, text_line);
    char comma;
    std::istringstream input_stream(text_line);
    // Read the name until a comma.
    std::getline(input_stream, r.name, ',');
    // Read the bread until a comma.
    std::getline(input_stream, r.breed, ',');
    input_stream >> r.age;
    input_stream >> comma;
    input_stream >> r.id;
    return input_stream;
}

您输入的代码如下所示:

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

编辑1:访问数据库记录
要查找第二只狗的品种:

  std::cout << database[1].breed << "\n";

请记住,索引从零开始。所以第二个元素位于索引1。

编辑2:按数字访问字段
按数字访问字段的问题是字段是不同的类型。但是,这可以通过返回所有内容的字符串来解决,因为所有类型都可以转换为字符串:

struct Record  
{
    std::string name;
    std::string breed;
    int         age;
    int         id;
    std::string operator[](int field_index);
    std::string operator[](const std::string& field_name);
};
std::string Record::operator[](int field_index)
{
    std::string value;
    std::ostringstream value_stream;
    switch (field_index)
    {
        case 0:  value = name; break;
        case 1:  value = breed; break;
        case 2:  
            value_stream << age;
            value = value_stream.str();
            break;
        case 3:  
            value_stream << age;
            value = value_stream.str();
            break;          
    }
    return value;
}

std::string Record::operator[](const std::string& field_name)
{
    std::string value;
    std::ostringstream value_stream;
    if (field_name == "name") value = name;
    else if (field_name == "breed") value = breed;
    else if (field_name == "age")
    {
        value_stream << age;
        value = value_stream.str();
    }
    else if (field_name == "id")
    {
        value_stream << id;
        value = value_stream.str();
    }
    return value;
}

恕我直言,首选项应该是通过不被视为数组的成员名称来引用结构的成员。将struct视为数组的一个问题是字段具有不同的类型。 C ++变量仅是一种类型,函数只能返回一种类型。您可以通过使用union来增加复杂性,其中tuple将具有类型ID字段或'.'。最简单的方法是使用List表示法按成员进行访问。