IO文件代码不一致



我的函数的输出不一致。该函数假设打开一个文件,然后从文件中提取整数,然后将整数设置为数组。如果有20个整数,我会遇到从文件提取到数组的问题。当我尝试这样做时,我看到"数组超出了界限"

如果文件名不正确,或者文件上下文中没有整数,则该函数还用于定制提示。这两者似乎都正常工作。

如有任何帮助,我们将不胜感激。

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;
}

您的问题描述听起来像是给出了一个元素太少的数组。您可能需要考虑使用std::vector<int>并将元素读取到ths中,例如

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

最新更新