#include <iostream>
#include <fstream>
#include <vector>
#include <stdlib.h>
usingnamespace std;
void readingValues(std::ifstream& myFile);
int main()
{
ifstream myFile;
myFile.exceptions(ifstream::failbit | ifstream::badbit);
try{
myFile.open("integers.txt",ios::in);
readingValues(myFile);
myFile.close();
}catch(std::ifstream::failure e){
cout<<"Failed to open the file integers.txt!";
}
return 0;
}
void readingValues(std::ifstream& myFile){
vector<int> dynamicArray;
int myFileValues;
while (myFile >> myFileValues) {
dynamicArray.push_back(myFileValues);
}
cout << "Values Stored In Array:\n";
for (int i=0; i<dynamicArray.size(); i++) {
cout << dynamicArray[i] << '\n';
}
cin.get();
}
now the problem is when the control exits the "while loop" in the function "readingValues(std::ifstream& myFile)it goes straight to catch block ??? any idea why? and how to fix it?
you're trying to tell me exception handling is useless stuff? if the file is not there and i try to open the file so definitely things will go wrong so that's why i have to use exception handling...
Thank you very much but if I remove line 13! then if the file is not there my program will crash, i am handling the exception?
That's true. On the other hand, when the input extraction on line 39 fails an exception is going to be thrown. And since there aren't associated try-and-catch blocks in readingValues, that exception is not going to be caught in the function. The code on line 32 and below is currently unreachable.
Your code would be much simpler without exceptions.
Here's one way you could write it with exceptions enabled on stream operations: