从.txt文件中读取双精度数据到双数组c ++中 [英] Read doubles out of .txt file into double array c++

查看:361
本文介绍了从.txt文件中读取双精度数据到双数组c ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个需要大量股票价格的程序。我有这些价格存储在.txt文件,每行一个双。有一个未知数(可能是数千)。我不能得到数据到一个数组,我可以操纵。我已经无法解决这个问题了几个小时了。每当我尝试读取文件中的数据,然后将其转换为双精度,我得到奇怪的线程错误,程序挂起。任何人都可以告诉我如何读取一个未知数量的双精度数组。

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.4000000000000

50.8000000000000

50.8000000000000

50.5000000000000

50.5000000000000

50.2100000000000

50.2100000000000

49.1500000000000

49.1500000000000

48.5000000000000

48.5000000000000

感谢

推荐答案

从我看到的代码中看到的两件事(已在评论中提到):

Two things obvious from the code I see (already mentioned in comments):


  1. 不要增加 x

  2. o增量,当双精度元素没有元素时,您访问 doubles [x] ,x == 0。这是未定义的行为。您需要提前分配元素或使用 push_back 根据需要生成向量。

  1. You don't increment x.
  2. 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.

这篇关于从.txt文件中读取双精度数据到双数组c ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆