如何将文件从文件读取到数组中

How to Read Lines From a File Into an Array

本文关键字:文件 数组 读取      更新时间:2023-10-16

我试图使用Fstream将文件从文件中读取到数组中,然后将它们打印出来。我尝试通过使用for loop和a Getline命令来执行此操作,但是该程序一直在崩溃,并给我"抛出:写访问违规"消息。我应该在程序中修复某些问题,还是有更好的方法来执行此操作?

文件文本:

Fred Smith 21
Tuyet Nguyen 18
Joseph  Anderson 23
Annie Nelson 19
Julie Wong 17

代码:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    cout << "Harrison Dong - 7/21/17" << endl;
    string fileStuffs[4];
    ifstream fin;
    fin.open("C:\Users\Administrator\Documents\Summer 2017 CIS 118-Intro 
to Comp. Sci\Module 17\firstLastAge.txt");
    if (!fin.is_open()) {
        cout << "Failure" << endl;
    }
    for (int i = 0; i < 5 && !fin.eof(); i++) {
        getline(fin, fileStuffs[i]);
        cout << fileStuffs[i] << endl;
    }
    fin.close();
    system("Pause");
    return 0;
}

谢谢!

有更好的方法吗?

是。使用std :: vector。

#include <iostream>
#include <fstream>
#include <string>
#include <vector> // added to get vector
int main() {
    using namespace std; // moved to restrict scope to a place I know is safe.
    cout << "Bill Pratt - 7/21/17" << endl; // changed name
    vector<string> fileStuffs; // vector is a smart array. See documentation link 
                               // above to see how smart
    ifstream fin("C:\Users\Administrator\Documents\Summer 2017 CIS 118-Intro to Comp. Sci\Module 17\firstLastAge.txt");
    if (!fin.is_open()) {
        cout << "Failure" << endl;
    }
    else // added else because why continue if open failed?
    {
        string temp;
        while (getline(fin, temp)) // reads into temporary and tests that read succeeded.
        {
            fileStuffs.push_back(temp); // automatically resizes vector if too many elements
            cout << fileStuffs.back() << endl;
        }
    }
    // fin.close(); file automatically closes on stream destruction
    return 0;
}