【问题标题】:Loading records into dynamic array将记录加载到动态数组中
【发布时间】:2015-08-07 11:05:11
【问题描述】:

我正在尝试将文本文件中的一些记录加载到动态数组中。

记录用逗号分隔

eg: lost,cat,female,persian,0 3,black

这是我目前所拥有的:

struct Pet{

      char status[6];
      char petType[4];
      ...
}

void loadRecords(char * filename, Pet * petPointer, int count){

      ifstream fin;
      Pet* petPointer = new Pet[count];

      fin.open(filename); 

      for (int i = 0; i < count; i++)
      {
           while (fin.good())
           {
                getline(fin, petPointer->status[i], ',');
                ...
           }
      }
}

这将返回错误“没有重载函数“getline”的实例与参数列表匹配”

将这些记录加载到数组中的最佳方法是什么?

【问题讨论】:

  • 使用#include &lt;iostream&gt;并以std::为前缀。

标签: c++ arrays dynamic getline


【解决方案1】:

您将字符串用作数组,并将数组用作指针。这是有效的,因为字符串是数组,数组是指针,但这不是您想要的。 你应该这样做:

getline(fin, petPointer[i].status,  ',');

将数组称为指针 (petPoitner) 有点令人困惑。它是一个指针,因为它是一个数组,但您打算将它用作数组。

如果你想在酷炫的c处事方式中使用指针,你可以这样做:

Pet* pets = new Pet[count];
Pet* iter = pets;

while(...){
    getline(fin, iter->status);
    iter++;
}

无论哪种方式,在这两种方式中,您可能仍然应该检查插入的内容是否超过了您保留的内存。

【讨论】:

    猜你喜欢
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 2014-07-13
    • 2020-10-10
    • 1970-01-01
    相关资源
    最近更新 更多