Question

I have an input file as such:

3  5
7  4
10 5
8  2
12 9

How can I store only the first column of those numbers in a vector (3, 7, 10, 8, 12)? The numbers are separated by spaces and if I do the following code below, only the second column of numbers is stored in the vector instead of the first.

if (arrivalFile) {
    while (arrivalFile >> first_arrival) {
      myVector.push_back(first_arrival);
    }
    for (int i = 0; i < myVector.size(); i++) {
      myVector.erase(myVector.begin() + (i));
      cout << myVector[i] << endl;
    }
}
Was it helpful?

Solution

You need to remove the even location correctly

However, easiest way will be to use a dummy variable

int dummy ;
if (arrivalFile) {
    while (arrivalFile >> first_arrival >> dummy ) {
      myVector.push_back(first_arrival);
    }
}

OTHER TIPS

You can do

while (arrivalFile >> first_arrival) {
  myVector.push_back(first_arrival);
  int dummy;
  arrivalFile >> dummy;
}

No need of the erase, just:

while (arrivalFile >> first_arrival) {
  myVector.push_back(first_arrival);
  int skip;
  arrivalFile >> skip;
}

Read first value into number and second into dummy variable( just to empty stream).

std::fstream myfile("data.txt", std::ios_base::in);

int number, dummy;
std::vector<int> vNumbers;
// test file open   
if ( myFile) { 
    while ( myfile >> number >> dummy)
    {
        vNumbers.push_back( number);              // insert number into vector
    }
} else {
    throw std::runtime_error( "can't open file"); // signal run time failure
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top