Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Where must I have a file in order to open it in Visual Studio 2015 using ifstrea

ID: 3768594 • Letter: W

Question

Where must I have a file in order to open it in Visual Studio 2015 using ifstream? The file is a picture pgm file. Please give any tips on what else I need in my code such as file location or etc or simply where to put my file.Here is my code to open the file:

bool ok = false;
string fn = "";
do
{
if (fn.size()==0) cout << "filename? ";
else cout << "can't open "<<fn<<". re-enter filename: ";
cin >> fn;
cout << "trying to open file " << fn << endl;
ifstream ifs(fn); // make sure we can open the file.
if (ifs) ok = true;
if (ok)
cout << "file opened OK."<<endl;
else
cout << "problem opening file"<<endl;
} while (!ok);

Explanation / Answer

//Corrected version of your Program:

bool ok = false;
string fn = "";
do
{
if (fn.size()==0) cout << "filename? ";
else cout << "can't open "<<fn<<". re-enter filename: ";
cin >> fn;
cout << "trying to open file " << fn << endl;
ifstream ifs(fn.c_str());   
if (ifs) ok = true;
if (ok)
cout << "file opened OK."<<endl;
else
cout << "problem opening file"<<endl;
} while (!ok);  

//========================================
Explanation:

Note the line which is bold in the program. i

ifstream ifs(fn.c_str());

'fn' is the string to hold the filename read from the user. We have to use the c_str() function

to make the user input string as null terminated. (we know that every string has to be null terminated).

Now this filename can be easily opened by ifstream to read.

I tested the code . It was properly executed now.

*Also you have to place the file in proper folder which contains your source code.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote