Reputation: 21
The output from my function is being inconsistent. The function is suppose to open a file then extract integers from the file and then set the integers into an array. I am having problems extracting from the file to the array if there are 20 integers. When I try to do this, I am seeing that the "array is outside of bounds."
The function is also suppose to cout prompts if the file name is incorrect or if the file does not have an integer in its context. Both of these seem to be working properly.
Any help would be greatly appreciated.
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;
}
Upvotes: 1
Views: 161
Reputation: 153935
Your problem description sounds as if you give an array which has too few elements. You might want to consider using a std::vector<int>
and read elements into ths, e.g.
std::vector<int> array;
array.assign(std::istream_iterator<int>(infile), std::istream_iterator<int>());
Upvotes: 1