open new file each loop iteration

D

Danny Anderson

Hola, C++ folk!

I want to have a do...while loop that works with a different file each
iteration, prompting the user for the file name to open and write.

The problem I am having is that the second time around the loop, my code
skips the file name prompting bit, using the file name from iteration number
1. I have seen this kind of problem before, but I can't remember how to
deal with it correctly. Code snippet below

Comments and suggestions appreciated...

Thanks!
Danny

/*--- start code --- */
do
{
/* prompt for output file, using the file name in brackets if
* no file name is give (i.e., the user hits return). This will overwrite
* the contents of the file if this file is not empty!!
*/
cin.clear();
output_file_name.erase();

cout << "Output file? [bldg_report] ";

getline(cin, output_file_name);
if(output_file_name.empty())
{output_file_name="bldg_report.csv";}
else
{output_file_name+=".csv";}

dataOut_report.open(output_file_name.c_str());
if(!dataOut_report)
{cout << "ERROR: couldn't open output file..."; return 1;}
else
{cout << output_file_name <<" opened OK, ready to start..." << endl;}



cout << "Enter name for this building: ";
getline(cin, building_name);
cout << "Enter short description: ";
getline(cin, building_description);

dataOut_report << building_name << endl;
dataOut_report << building_description << endl;

dataOut_report.close();
}while(user_is_not_finished() );
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top