簡體   English   中英

C++ 從文本文件中讀取

[英]C++ reading from a text file

我正在嘗試從兩個文本文件中讀取。 一次一個,但我不斷收到無法打開文件的消息。 我試圖確保它們在同一個目錄中,但它仍然不起作用。 誰能告訴我哪里出錯了?

這是 class 的構造函數,它從 2 個文本文件中讀取並填充兩個不同的 arrays。

這是代碼:

#include <iostream>
#include <fstream>
#include "student.h"
#include "staff.h"
#include "studentstaff.h"

using namespace std;

studentstaff::studentstaff()
{
    p = new Student[5];
    p1 = new Staff[5];

    ifstream file;
    file.open("Student.txt");

    if (!file)
    {
        cout << "File couldn't open." << endl;
    }
    else
    {
        int studentID;
        string firstName;
        string lastName;
        string DOB;
        char program;
        int credit;
        int startYear;
        double GPA;

        file >> studentID >> firstName >> lastName >> DOB >> program >> credit >> startYear >> GPA;

        while (file)
        {
            for (int i = 0; i < 5; i++)
            {
                file >> studentID >> firstName >> lastName >> DOB >> program >> credit >> startYear
                    >> GPA;
                p[i].setStudent(
                    studentID, firstName, lastName, DOB, program, credit, startYear, GPA);
            }
        }
        file.close();
    }

    ifstream stafffile;
    stafffile.open("staff.txt");

    if (!stafffile)
    {
        cout << "File couldn't open." << endl;
    }
    else
    {
        string employeefstname;
        string employeelstname;
        int ID;
        string phonenum;
        int datehired;
        char Code;
        double salary;
        stafffile >> employeefstname >> employeelstname >> ID >> phonenum >> datehired >> Code
            >> salary;

        while (stafffile)
        {
            for (int i = 0; i < 5; i++)
            {
                stafffile >> employeefstname >> employeelstname >> ID >> phonenum >> datehired
                    >> Code >> salary;
                p1[i].setfirstname(employeefstname);
                p1[i].setlastname(employeelstname);
                p1[i].setID(ID);
                p1[i].setphonenum(phonenum);
                p1[i].setdatehired(datehired);
                p1[i].setbonuscode(Code);
                p1[i].setsalary(salary);
            }
        }
        stafffile.close();
    }
}

你應該這樣寫:

int i = 0;
while(file >> studentID >> firstName >> lastName >> DOB >> program >> credit >> startYear >> GPA){

    p[i].setStudent(studentID, firstName, lastName, DOB, program, credit, startYear, GPA);
    i++;
}

或者,如果輸入文件中恰好有 5 條記錄,則:

for(int i = 0; i<5; i++){

    file >> studentID >> firstName >> lastName >> DOB >> program >> credit >> startYear >> GPA;
    p[i].setStudent(studentID, firstName, lastName, DOB, program, credit, startYear, GPA);
}

還要檢查文件名file.open("Student.txt"); ,如果您犯了任何錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM