I'm attempting to create a program that takes a large number of stock prices. I have these prices stored in a .txt file with one double per row. There are an unknown number (probably thousands). I cannot get the data into an array which I can manipulate. I've been unable to solve this problem for a couple hours now. Whenever I attempt to read the data out of the file and then convert it to a double, I get weird thread errors and the program hangs. Can anyone show me how to read an unknown amount of doubles into an array.
string line;
vector<double> doubles;
fstream myfile ("/Users/jaychinnaswamy/Documents/PMHistory.txt",std::ios_base::in);
int x=0;
float a;
while (myfile >> a)
{
doubles[x]=a;
}
An example of the file structure is:
50.4000000000000
50.8000000000000
50.5000000000000
50.2100000000000
49.1500000000000
48.5000000000000
Thanks
Two things obvious from the code I see (already mentioned in comments):
- You don't increment
x
.
- Even w/o increment, you access
doubles[x]
with x==0 when doubles has no elements. That's undefined behavior. You need to allocate elements ahead of time or use push_back
to grow vector as needed.
You have created an empty vector here.
vector<double> doubles;
And here, you are indexing into the vector, as if it's not empty. It's still empty and you are accessing an invalid element.
doubles[x]=a;
Change that code to use std::vector::push_back()
.
doubles.push_back(a);
The code you have submitted has a few issues. As stated by others, you have instantiated an empty std::vector
and your code does assignments onto an index that does not exist. Since your problem revolves around an unknown amount of elements (dynamic size), use the push_back
method of std::vector
. I would advise you not convert from float
to double
through a
. You know the data is a double
and you want to store it as a double
, so use double
. Since this is just a piece of your code, you can utilize a for
loop to make double a
scope bound to the loading of the data.
Your code can be rewritten into:
std::ifstream myfile("/Users/jaychinnaswamy/Documents/PMHistory.txt");
std::vector<double> doubles;
for (double a; myfile >> a;) {
doubles.push_back(a);
}
However, if you don't require data verification, you know the file contains only doubles, and you really just want to import the numbers, then use the range constructor for std::vector
to read the file for you via std::istream_iterator
.
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::ifstream myfile("/Users/jaychinnaswamy/Documents/PMHistory.txt");
std::vector<double> doubles{(std::istream_iterator<double>(myfile)),
std::istream_iterator<double>()};
}
Pay special attention to the ()
around the first iterator argument of the std::vector
range constructor. Without the ()
will result in syntactic ambiguity, also known as the "most vexing parse".