2011-11-21 86 views
1

这里是我的问题,我想从一个文件"beginningbalance.dat"读入数据,包含以下内容:从文件中读取到2阵列

111 
100.00 
200.00 
50.00 
222 
200.00 
300.00 
100.00 

我想要做的是111customer_number[0]什么和222customer_number[1]。对于new_balance[0],我想在111new_balance[1]下加上222下的数字。

#include <iostream> 
#include <fstream> 
using namespace std; 



int main() 
{ 
    int count = 0; 
    double val1, val2, val3, sum; 
    int customer_number[2];//Array for holding customer number from file. 
    double new_balance[2];//Array for holding added values from file. 

    ifstream beginning_balance; 
    beginning_balance.open("beginningbalance.dat"); 



    while(beginning_balance) 
    { 
     beginning_balance >> customer_number[count]; 
     beginning_balance >> val1; 
     beginning_balance >> val2; 
     beginning_balance >> val3; 

     sum = val1+val2+val3; 

     new_balance[count] = sum; //Supposed to read in customer id number then 3 values from files, then starts itself over and reads a new customer number for the new array element. 
     count++;     // 
    } 

    cout<<val1<<" "<<val2<<" "<<val3<<"\n\n";//Testing values being read in 

    cout<<"Customer Number #"<<customer_number[0]<<endl;//Should read Customer Number # 111 
    cout<<"New Balance $"<<new_balance[0]<<endl; 
    cout<<"Customer Number #"<<customer_number[1]<<endl;//Should read Customer Number # 222 
    cout<<"New Balance $"<<new_balance[1]<<endl; 



    system("pause"); 
    return 0; 
} 

我的输出是

100 -858993460 -858993460 

Customer Number #111 
New Balance $-1.71799e+009 
Customer Number #0 
New Balance $5.48413e-322 
Press any key to continue... 

{我有我的val1,val2,val3,并sum设置为int当它应该有什么事情,让浮点数,我也只允许1个元素为每个阵列。 }

+0

您是否尝试过使用调试器来看看,看看什么正在执行程序时发生? – crashmstr

回答

2

这可能不是全部的错误,但它至少它的一部分:

int customer_number[1];//Array for holding customer number from file. 
double new_balance[1];//Array for holding added values from file. 

您已声明这些[1]意思是“1个索引为0的元素”。如果你想索引0和1,那么你应该使用[2]。通过溢出你的数组边界,你会破坏附近其他变量的内存,这可能解释了不好的平衡值。 (但也许val2和val3值不好)

但是由于你的代码允许你读取任意数量的数据集,所以你应该考虑使用stl :: vector或类似的对象,或者可能是stl: :包含客户编号和余额的结构/类作为单个对象的向量。

+0

你是对的改变数组大小,这只是在内存中的失误与数字名称混淆。但是这并没有解决它读取正确的值,我还没有到矢量。 – sircrisp

1

当数组索引从零开始时,数组定义不会。你的问题之一是你只定义了数组和new_balance每个包含一个条目,然后你在不同的索引处输入两个值。这会覆盖内存,并可能导致意外的行为。

1

数组声明为

int customer_number[1]; 

只有1元,指数为0。很可能,你想拥有它的多个元素。尝试用例如[1]代替|8](并且要小心访问它的每个索引在0和7之间= 8-1)

另外,编译您的代码,并启用所有警告和调试信息。在Linux上,这意味着g++ -Wall -g并改善您的代码,直到您根本没有任何警告。

了解如何使用调试器(例如Linux上的gdb),特别是如何在调试器下逐步运行程序以及如何检查变量。

1

另外请注意,你应该声明

float val1, val2, val3, sum; 

double val1, val2, val3, sum; 

,如果你希望积累浮点值的数据量

+1

这是我的问题哈哈。 – sircrisp

+1

太棒了!你应该把Bogatyr的答案当作是为你解决问题的答案 - 谢谢。 – Rup