繁体   English   中英

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

[英]Reading in a comma delimited .txt file and putting into array

假设有一个名为“dogs.txt”的文件,它具有名称、品种、年龄和 id 编号。 因此,我想将每个元素读入我的 c++ 程序中,这样它们就可以被类似 dog[0,2] 访问,这将给我第 0 只狗的第 2 个元素(品种)。

例子:

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

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

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

看起来您的输入数据是每行(行)一条记录
所以,让我们 model 行:

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++ 变量喜欢只有一种类型,函数只能返回一种类型。 您可以通过使用具有类型 ID 字段或者可能是tupleunion来增加复杂性。 最简单的方法是使用'.'按成员访问。 符号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM