Vroryn
Vroryn

Reputation: 125

Reading a text file into a vector from the command line

Whenever I try to see the contents inside the vector I get "segmentation fault" any idea why that is? Do I not read in the values properly?

#include <iostream>
#include <cstdlib> // atoi function
#include <vector>
#include <fstream>

using namespace std;

vector<int> list ; // global vector

int main (int args , char * argv[])
{
  ifstream in(argv[1]);
  //ofstream out(argv[2]);
  int listSize = atoi (argv[2]);

  cout << listSize << endl;

  int i = 0;
  cout << argv[1] << endl;
  in.open(argv[1]);
  while (i < listSize)
  {
    in >> list[i];
    cout << "test2" << endl;

    i++;
  }
  in.close();

  for( int k=0; k <listSize; k++){
    cout<< list[k] << endl;
  }


  return 0;
 }

the text file contains these numbers:

 5 6 7 11 12 13

Upvotes: 0

Views: 350

Answers (2)

Dennys Barreto
Dennys Barreto

Reputation: 51

Read what's in the file using getline. See sample code below:

ifstream InFile(argv[1], ios::in); /*Open file from arg[1]*/ std::string LineContent; getline(InFile, LineContent); /*Save line per line */

With your line saved in a string, you can now transfer the data from that string to the vector, see:

vector<int> list; list.push_back(atoi(LineContent.c_str()));

Now, you can print out what's in the file:

for (int i = 0; i < list.size(); i++) cout << list[i] << endl;

Upvotes: 0

Thomas Matthews
Thomas Matthews

Reputation: 57749

A vector doesn't automatically come with slots. You have to either reserve slots or use push_backto append items to the vector:

//...
int value;
in >> value;
list.push_back(value);

Upvotes: 2

Related Questions