如何从文本文件中读取数据并将其加载到矢量中?

问题描述:

我想从文本文件中读取使用结构的数据并将其加载到向量中。如何从文本文件中读取数据并将其加载到矢量中?

所以我写了一个以下做到这一点,但我没有编译。我不知道什么是错的。

<我做了什么>

  1. 文本文件包含的数据如下:

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

(整数数组[3],整数,整数,整数,整数,整数,浮点数,布尔值)

2.我声明一个结构包含以下数据类型来将数据加载到向量中;

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):错误C2661:'未完成::未完成':没有超载函数需要10个参数

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

感谢,

seihyung

+0

添加'unfinished'末结构定义('}未完成;') – 2015-04-03 14:27:14

+0

Praneeth,我试过你说的,但没有奏效。 – 2015-04-03 14:31:54

+0

可能的重复项:[* C++ read file structure](https://www.google.com/search?q=*+c%2B%2B+read+file+structure&ie=utf-8&oe=utf-8),in换言之,在发布问题之前搜索互联网和*。 – 2015-04-03 14:42:31

您需要添加一个构造函数,需要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; 
    } 
    .... 
}; 
+0

haavee,我添加了一个构造函数来结构和错误消息已经消失。但没有任何东西在屏幕上显示出来。换句话说,我需要检查代码....无论如何,你的建议工作,并感谢! – 2015-04-03 15:17:38