【问题标题】:How to Read Lines From a File Into an Array如何将文件中的行读入数组
【发布时间】:2017-11-23 00:31:43
【问题描述】:

我正在尝试使用 fstream 将文件中的行读取到数组中,然后将它们打印出来。我尝试通过使用 for 循环和 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;
}

谢谢!

【问题讨论】:

  • string fileStuffs[4];for (int i = 0; i &lt; 5 &amp;&amp; !fin.eof(); i++) 允许索引到 5 的 4 个元素的数组。这不是一个好计划。
  • 您好 user4581301。我不认为 .eof 是问题,因为我尝试使用单个语句而不是循环 (getline(fin, fileStuffs[0]); getline(fin, fileStuffs[1]); etc) 来完成它并且它有效对于我写的第一个,但停止为两个或多个 getline 语句工作。
  • EOF 在这里是个小插曲,但需要注意。第一条评论中概述了该问题。您正在越界访问fileStuffs
  • 不过,当我将其更改为 i

标签: c++ arrays file-io


【解决方案1】:

有没有更好的方法来做到这一点?

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

【讨论】:

    猜你喜欢
    • 2010-12-25
    • 2022-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    相关资源
    最近更新 更多