如何将文本文件中的数据读入结构

时间:2015-07-07 12:48:30

标签: c++ struct

我是C ++的新手,目前我正在尝试阅读非常基本的文本文件,如下所示:

Dr John Doe
British
2
Soccer
Swimming

我的预期输出应该如下:

My information
Name: John Doe
Nationality: British
I have 2 hobbies:
1. Soccer
2. Swimming

我的标题文件:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;

const int MAX = 80;
const int MAXNO = 5;
enum Title {Miss, Mrs, Mr, Dr, Unknown};
struct Date
{
 int day; 
 int month;
 int year;
};

struct MyInfo
{
    char name [MAX];
    char national [MAX];
    int noOfHobbies;
    char hobby [MAXNO][MAX];
};

void getMyInfo (fstream& , char[] , MyInfo&);
void displayMyInfo (MyInfo);

我的职能:

#include "Lab_1.h"
void getMyInfo (fstream& afile,char fileName[], MyInfo& x) {
    afile.open (fileName);

    if (!afile)
    {
        cout << "Binary file " << fileName << " opened for creation failed" << endl;
        exit (-1);
    }

    cout << "\n" << "Begin reading of " << fileName << endl;

    string line;
    while(getline(afile, line))
    {
        afile >> x.national;
        afile >> x.noOfHobbies;*/
        if (afile >> x.name >> x.national >> x.noOfHobbies) {
            cout << "Name: " << x.name << ", " 
                << "National: " << x.national << ", " 
                << "noOfHobbies: " << x.noOfHobbies << ", " 
                << endl;
        }
    }
}    

void displayMyInfo (MyInfo x) {

}

我的主要职能:

#include "Lab_1.h"

int main () {
    fstream afile;
    MyInfo x;
    string fileName;

    getMyInfo(afile,"textfile.txt",x);

    //displayMyInfo(x);

    afile.close ();

}

上面的代码没有输出任何内容,因为我只是将我理解的所有内容放在论坛上并提出类似问题。虽然我已经停留了1天,尽管我已经做了很多研究,但是大多数人建议使用我现在不熟悉的矢量,那么有人可以给我一个解决这个问题的方法吗?非常感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

madness 善意的随机行为:

<强> Live On Coliru

$VAR1 = {
          'ResultSet' => {
                           'result' => [
                                         {
                                           'rank' => '999999',
                                           'term' => 'shampoo'
                                         },
                                         {
                                           'rank' => '999999',
                                           'term' => 'Beauty',
                                           'url' => '/search/results.jsp?Ntt=shampoo&N=359434'
                                         },
                                         {
                                           'url' => '/search/results.jsp?Ntt=shampoo&N=359449',
                                           'term' => 'Baby, Kids & Toys',
                                           'rank' => '999999'
                                         }
                                       ]
                         }
        };

/search/results.jsp?Ntt=shampoo&N=359434
/search/results.jsp?Ntt=shampoo&N=359449