2015-02-09 21 views
0

我想從2個不同的文本文件中提取double值,並將它們放入數組中。下面是代碼片段:從文件中提取double值到數組中

#include <cstdlib> 
#include <iostream> 
#include <fstream> 

using namespace std; 
int main() 
{ 
    int p; 
    cout<<"Enter number of ordered pairs: "; 
    cin>>p; 
    cout<<endl; 
    double x[p]; 
    ifstream myfile("x.txt"); 
    while (myfile.good()) 
    { 
     myfile>>x[p]; 
     cout<<x[p]<<endl; 
    } 
    double testx = x[4]+x[3]+x[2]+x[1]+x[0]; 
    cout<<endl<<"The sum of the values of x are: "<<testx<<endl<<endl; 
    double y[p]; 
    ifstream myfile2("y.txt"); 
    while (myfile2.good()) 
    { 
     myfile2>>y[p]; 
     cout<<y[p]<<endl; 
    } 
    double testy = y[4]+y[3]+y[2]+y[1]+y[0]; 
    cout<<endl<<"The sum of the values of y are: "<<testy<<endl<<endl; system("PAUSE"); 
    return EXIT_SUCCESS; 
} 

我不認爲值正在由於通過testxtexty檢查它存放不當,該值的總和不是預期的。

+0

[C/C++:數組大小在運行時不允許動態分配?](http://stackoverflow.com/questions/737240/cc-array-size-at-run-time- wo-dynamic-allocation-is-allowed) – CoryKramer 2015-02-09 12:25:09

+0

您正在打印這些值,因此您可以根據此假設而不是總和。什麼是輸入,輸出預期輸出(包括打印輸出值)。 – stefaanv 2015-02-09 12:25:31

+0

你不能用變量'p'來調整數組'x'。編譯時需要知道大小,而不是運行時(禁止某些編譯器擴展) – CoryKramer 2015-02-09 12:25:42

回答

4

你寫出來的陣列的界限:你寫到x[p]y[p],其中xy是大小p的陣列,從而有效的索引,從0p-1

更不用說運行時大小的數組不是標準的C++;一些編譯器(如GCC)支持它們作爲擴展,但最好不要依賴它們。

當需要在C++中一個動態大小的陣列,使用std::vector

int p; 
cout<<"Enter number of ordered pairs: "; 
cin>>p; 
cout<<endl; 
std::vector<double> x; 
ifstream myfile("x.txt"); 
double d; 
while (myfile >> d) 
{ 
    x.push_back(d); 
    cout<<b.back()<<endl; 
} 

DTTO爲y

請注意,我改變了循環條件—你沒有測試輸入操作的結果。 More info

此外,如果數字是任意浮點值,請記住它們在許多情況下由於舍入誤差和表示不精確性而導致cannot be simply compared for equality