-1

I am writing a fairly simple code to enter integers stored in a file into an array of moderate size, but on compiling and running the code, it gives Segmentation fault error, can anyone please correct me where I am making a mistake, the code is

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

int main()
{
    int arr[100000];
    ifstream f;
    f.open("IntegerArray.txt");
    string line;

    if (f.is_open())
    {
        int i=0;
        while (f.good())
        {
            getline(f,line);
            arr[i++] = atoi(line.c_str());
        }
        f.close();
    }
    else
        cout<<"file not open";
    return 0;
}
Ivan Pavičić
  • 1,083
  • 2
  • 16
  • 28

1 Answers1

2

After rading a line from a file with getline(), the stream should be checked for potential errors, for example with .fail(), which:

Returns true if either (or both) the failbit or the badbit error state flags is set for the stream.

while (f.good())
{
    getline(f,line);

    if (f.fail()) {
        cout << "Corrupt data" << endl; // example output
        break;
    }

    // everything ok, continue with logic
    arr[i++] = atoi(line.c_str());
}
Ivan Pavičić
  • 1,083
  • 2
  • 16
  • 28