c++ - 我无法让我的程序在函数中读取我的文件

标签 c++ arrays

我似乎无法弄清楚为什么我的代码没有读入要在 switch case 中使用的数据。当我将它写入文件时,它只会产生垃圾。谁能帮忙?

void readData(Name element[], int size)
{
    ifstream infile("treeData.txt");

    int index = 0;
    string line, common, scientific, family;
    int name;

    infile.open("treeData.txt");
    {           
        {
            while((index < size) && (infile >> name >> common >> scientific >> family))
            {
                if(name >= 0 && name <= 100)
                {
                    infile >> element[index].treeID;
                    element[index].treeID = name;
                    infile >> element[index].commonName;
                    element[index].commonName = common;
                    infile >> element[index].scientificName;
                    element[index].scientificName = scientific;
                    infile >> element[index].familyName;
                    element[index].familyName = family;
                    index++;
                    size = index;
                }   
                else
                    cout << "The file was not found!";
            }
        }
    }       
    infile.close();
}

最佳答案

您的实现应利用 C++ IOStreams 库的可扩展性功能。您可以创建 operator >> 的重载,以便任何输入流都可以将数据提取到 Name 对象中。还建议不要将数据提取到数组中(就像您在 readData 函数中尝试过的那样),而是将其提取到单个对象中。这样就可以在此功能之上构建代码。这也是一种更合乎逻辑和更直接的提取方式:

std::istream& operator>>(std::istream& is, Name& n)
{
    if (!is.good())
        return is;

    int id;
    std::string line, common, scientific, family;

    if (is >> id >> common >> scientific >> family)
    {
        if (id >= 0 && id <= 100)
            n.treeID = id;

        n.treeID         = name;
        n.commonName     = common;
        n.scientificName = scientific;
        n.familyName     = family;
    }
    return is;
}

现在我们有了提取器,我们可以继续创建一个 Name 对象数组,并为每个元素使用提取器:

std::ifstream infile("treeData.txt");
std::array<Name, 5> names;

for (auto name : names)
{
    infile >> name;
}

关于c++ - 我无法让我的程序在函数中读取我的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20010749/

相关文章:

c++ - 如何在不使用指针的情况下编写对 10 个整数数组的引用?

javascript - 向数组对象添加属性

c++ - 单例实例作为静态字段与 getInstance() 方法中的静态变量

c++ - 将 'this' 转换为 std::shared_ptr

从 2x3 数组矩阵计算行列式

java - 二进制数据图像转换不等于同一图像的jpg

c - 使用指针存储字符串

java - 同步截屏 (ffmpeg) 和从网络摄像头捕获 (OpenCV)

c++ - #将所有 .cpp 文件包含在一个编译单元中?

c++ - map.insert : "Invalid arguments" error with pair<enum, vector <*>>