How to read a file into vector in C++?
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.
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.
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.
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.