Reputation: 157
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;
}
}
Upvotes: 0
Views: 601
Reputation: 29724
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
}
Upvotes: 0
Reputation: 350
No need of the erase, just:
while (arrivalFile >> first_arrival) {
myVector.push_back(first_arrival);
int skip;
arrivalFile >> skip;
}
Upvotes: 0
Reputation: 47794
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);
}
}
Upvotes: 2
Reputation: 1
You can do
while (arrivalFile >> first_arrival) {
myVector.push_back(first_arrival);
int dummy;
arrivalFile >> dummy;
}
Upvotes: 0