如何从txt文件中正确提取数据

时间:2019-05-19 11:29:58

标签: c++ file error-handling file-handling

每当我尝试读取文本文件时,都会遇到流问题和提取问题,并且无法在控制台输出上正确处理它,并且会产生大量垃圾。
谁能向我展示使用代码中使用的功能的正确方法?我是初学者。

#include <iostream>
using namespace std;
#include <string>
#include <cstring>
#include <fstream>

struct student {
    char rollnum[28];   //struct to store data
    char course[4];
    int md, ss, fn;
};
int main()
{
    ifstream fin("okhi.txt");   //file openning here
    if (fin)
    {

        student dat[21];
        string h1, h2;                //strigs to get 1st two lines as it is
        getline(fin, h1); fin.clear();
        getline(fin, h2); fin.clear();
        cout << h1 << endl << h2 << endl;

        for (int x = 0; x < 21; x++)
        {
            dat[x].md = dat[x].ss = dat[x].fn = 0;

        }
        for (int x = 0; x < 21; x++)
        {
            fin.getline(dat[x].rollnum, 28);
            cout << dat[x].rollnum;
            fin.clear();
            fin.getline(dat[x].course, 4);
            cout << " " << dat[x].course;
            fin.clear();
            fin >> dat[x].md;
            cout << " " << dat[x].md;
            fin >> dat[x].ss;
            cout << " " << dat[x].ss;
            fin >> dat[x].fn;
            cout << " " << dat[x].fn<<endl;
            fin.clear();
            fin.ignore();

        }
        cout << dat[0].rollnum << endl;
    }
}

The text file i want to read & output m getting are shown

0 个答案:

没有答案