In: Computer Science
C++ code
a program should prompt the user for the name of the output file. The file should be opened for write operations. Values calculated by the program will be written to this file. The program must verify that the file opened correctly. If the file did not open, an error message should be printed and the user should be prompted again. This should continue until the user supplies a valid filename.
#include <iostream> #include <fstream> using namespace std; int main() { string fileName; ofstream o; while(true) { cout << "Enter a filename for output: "; cin >> fileName; o.open(fileName.c_str()); if(o.fail()) { cout << "Unable to open file." << endl; } else { break; } } cout << "Success in opening the file." << endl; o.close(); }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.