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

时间:2017-11-23 00:31:43

标签: c++ arrays file-io

我正在尝试使用fstream将文件中的行读入数组,然后将其打印出来。我尝试使用for循环和getline命令来执行此操作,但程序不断崩溃并向我发出" Exception Thrown:write access violation"信息。我应该在我的程序中修复一些东西,还是有更好的方法来做到这一点?

文件文字:

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;
}

谢谢!

1 个答案:

答案 0 :(得分:0)

  
    

有更好的方法吗?

  

是。 Use a 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;
}