How to read a file into vector in C++?
Solution 1
Your loop is wrong:
for (int i=0; i=((Main.size())-1); i++) {
Try this:
for (int i=0; i < Main.size(); i++) {
Also, a more idiomatic way of reading numbers into a vector and writing them to stdout is something along these lines:
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm> // for std::copy
int main()
{
std::ifstream is("numbers.txt");
std::istream_iterator<double> start(is), end;
std::vector<double> numbers(start, end);
std::cout << "Read " << numbers.size() << " numbers" << std::endl;
// print the numbers to stdout
std::cout << "numbers read in:\n";
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
}
although you should check the status of the ifstream
for read errors.
Solution 2
Just to expand on juanchopanza's answer a bit...
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
does this:
- Create
i
and set it to0
. - Set
i
toMain.size() - 1
. SinceMain
is empty,Main.size()
is0
, andi
gets set to-1
. Main[-1]
is an out-of-bounds access. Kaboom.
Solution 3
Just a piece of advice. Instead of writing
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
as suggested above, write a:
for (vector<double>::iterator it=Main.begin(); it!=Main.end(); it++) {
cout << *it << '\n';
}
to use iterators. If you have C++11
support, you can declare i
as auto i=Main.begin()
(just a handy shortcut though)
This avoids the nasty one-position-out-of-bound error caused by leaving out a -1
unintentionally.
Solution 4
1. In the loop you are assigning value rather than comparing value so
i=((Main.size())-1) -> i=(-1) since Main.size()
Main[i] will yield "Vector Subscript out of Range" coz i = -1.
2. You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.
Orgmo
Updated on April 24, 2020Comments
-
Orgmo about 4 years
I need to read from a
.data
or.txt
file containing a newfloat
number on each line into a vector.I have searched far and wide and applied numerous different methods but every time I get the same result, of a
Main.size()
of0
and an error saying"Vector Subscript out of Range"
, so evidently the vector is just not reading anything into the file.Note: the file is both in the folder and also included in the VS project.
Anyway, here's my code:
#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> using namespace std; int main() { vector<double> Main; int count; string lineData; double tmp; ifstream myfile ("test.data", ios::in); double number; myfile >> count; for(int i = 0; i < count; i++) { myfile >> tmp; Main.push_back(tmp); cout << count; } cout << "Numbers:\n"; cout << Main.size(); for (int i=0; i=((Main.size())-1); i++) { cout << Main[i] << '\n'; } cin.get(); return 0; }
The result I get is always simply:
Numbers: 0