2012-03-13 32 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