2012-03-13 27 views
1

我的函數輸出不一致。該函數假設打開文件,然後從文件中提取整數,然後將整數設置爲數組。如果有20個整數,我在從文件中提取數組時遇到問題。當我嘗試這樣做時,我看到「陣列超出界限」。IO文件代碼不一致

該函數還假設cout會提示文件名是否不正確或文件的上下文中沒有整數。這兩個似乎都正常工作。

任何幫助將不勝感激。

bool loadArrayFromFile(int a[], int &n) 
{ 
ifstream infile; 
string fileName; 
cout<<"Enter the name of file: "; 
cin>>fileName; 
infile.open(fileName.c_str()); 
if(!infile) 
{ 
    cout<<"File didn't open"<<endl; //if file name is incorrect or could not be opened 
    return false; 
} 
int count=0; //count values in file 
int elem=0; //keeps track of elements 
infile>>a[elem]; 
while(infile.good()) 
{ 
    elem++; 
    count++; 
    infile>>a[elem]; 
} 
if(!infile.eof()) 
{ 
    cout<<"Wrong datatype in file"<<endl; 
    infile.clear(); 
    infile.close(); 
    return false; 
} 
n=count; 
infile.close(); 
return true; 
} 
+0

我被告知程序在查看代碼時會自動將其向量化。所以這就是爲什麼我做矢量化的原因。 – user1188766 2012-03-13 00:23:26

回答

1

您的問題描述聽起來就像您提供的元素數量太少。您可能需要考慮使用std::vector<int>並將元素讀入到例如

std::vector<int> array; 
array.assign(std::istream_iterator<int>(infile), std::istream_iterator<int>()); 
+0

當程序查看代碼時,我被告知它會自動對它進行矢量化。所以這就是爲什麼我做矢量化的原因。 – user1188766 2012-03-13 00:24:40

+0

以及我還沒有學會如何在C++中使用向量 – user1188766 2012-03-13 00:25:09

+0

使用'std :: vector '和「向量化」是兩個完全不同的概念!後者適用於使用一次處理多個值的某些CPU操作,並且與資源分配無關。 – 2012-03-13 00:26:54