c++ - 如何从文本文件中读取数据并将其加载到 vector 中?

标签 c++ c++11 vector structure

我想使用结构从文本文件中读取数据并将其加载到 vector 中。

所以我写了下面的代码来做这个但是我编译失败了。我不知道出了什么问题。

<我做了什么>

  1. 文本文件包含如下数据;

835,5,0,0,1,1,8.994,0

(整数数组[3],整数,整数,整数,整数,整数, float , bool 值)

2.我声明了一个包含以下数据类型的结构,用于将数据加载到 vector 中;

struct unfinished
{
    int ans[3]; // contains answer
    int max;
    int st;
    int ba;
    int outs;
    int tri;
    float elapsed;
    bool fin;
};

3.我写了一个读取数据的代码如下;

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

struct unfinished
{
   int ans[3];
   int max;
   int st;
   int ba;
   int outs;
   int tri;
   float elapsed;
   bool fin;
};

vector<unfinished> read_rec(istream & is)
{
  vector<unfinished> rec;
  int ans[3];
  int max, st, ba, outs, tri;
  float elap;
  bool fini;

  while (is >> ans[0] >> ans[1] >> ans[2] >> max >> st >> ba >> outs >> tri    >> elap >> fini)
{
    rec.emplace_back(ans[0], ans[1], ans[2], max, st, ba, outs, tri, elap, fini);
}
return rec;
}

int main(void)
{
ifstream infile("unfin_rec.txt");
auto unfin = read_rec(infile);

vector<unfinished>::const_iterator it;

for (it = unfin.begin(); it != unfin.end(); it += 1)
{
    cout << it->ans[0] << it->ans[1] << it->ans[2] << "," << it->max << "," << it->st << "," << it->ba <<","<<it->outs<<","<<it->tri<<","<<it->elapsed<<","<<it->fin<< endl;
}

system("pause");
return 0;
}

我未能编译此代码。错误消息是:>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0(600): error C2661: 'unfinished::unfinished' : 没有重载函数需要 10 个参数

再次,我无法弄清楚这条消息的含义。请帮忙!

谢谢,

世亨

最佳答案

您需要添加一个构造函数,它接受 10 个参数并填充结构的成员,如下所示:

struct unfinished
{
    unfinished(int a0, int a1, int a2,
               int m, int s, int b, int o, int t,
               float e, bool b):
        max(m), st(s), ba(b), outs(o), tri(t), elap(e), fini(b) {
           ans[0]=a0, ans[1]=a1, ans[2]=a2;
    }
    ....
};

关于c++ - 如何从文本文件中读取数据并将其加载到 vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29433998/

相关文章:

c++ - 我应该使用 CCArray 在 cocos2d-x 中保存自定义 CCNode 吗?

c++ - 我在这个使用 std::regex 的正则表达式中犯了什么错误

matlab - 查找矩阵中所有零元素的邻居

C++将csv读入vector,getline()问题

C++11 标记元组

android - while循环中的一个变量没有改变,ndk/android

c++ - 模板化成员函数的语法

c++ - 什么是 std::unordered_map 的性能不错的散列器,它将我的 key 视为通用内存块?

c++ - 使指向基类指针的 std::vector 的指针指向派生类指针的 std::vector

json - 如何通过属性将 JSON 对象数组整理成包含每个对象属性向量的结构?