C++: Open File Multiple Times Before Exiting

  • Context: C/C++ 
  • Thread starter Thread starter Nusc
  • Start date Start date
  • Tags Tags
    C++ File
Click For Summary

Discussion Overview

The discussion revolves around how to implement functionality in C++ that allows a user to open a file multiple times before exiting the program. The focus is on coding techniques and user interaction within the program.

Discussion Character

  • Technical explanation
  • Exploratory

Main Points Raised

  • One participant presents a code snippet for reading data from a file but does not include a mechanism for reopening the file multiple times.
  • Another participant suggests using a loop to allow the user to open another file, proposing a character input to continue or exit.
  • A later reply indicates that the original poster has resolved their issue without providing details on the solution.

Areas of Agreement / Disagreement

The discussion does not reach a consensus on the implementation details, as the original poster's final solution is not shared, leaving the proposed looping mechanism unverified.

Contextual Notes

There are limitations in the provided code, such as error handling and user prompts, which are not fully explored or resolved in the discussion.

Nusc
Messages
752
Reaction score
2
Hi. I am required to ask the user to open a file multiple times before exiting the program. How do I do this?

void ReadData(vector <student> & section, int& num_Students,string& filename)
{
ifstream in;
count << "Please enter file name:" << endl;
cin >> filename;
in.open(filename.c_str());
if(in.fail())
{
// count << "Input file does not exist. Please enter the correct file name again:" << endl;

// while (i < = 3)
// {



count << "Input file does not exist. Now exiting program." << endl;
exit(1);
}
else
{
if(!in.eof())
{
in >> num_Students;
count <<"You have successfully opened "<< filename <<" and there are "<< num_Students <<" students in file."<< endl;
section.resize(num_Students);
for (int i=0; i<section.size();i++)
{
in >> section.at(i).first >> section.at(i).last >> section.at(i).id;
in >> section.at(i).final >> section.at(i).midterm;

section.at(i).lab_scores.resize(5);

for (int j=0;j<5;j++)
in>>section.at(i).lab_scores.at(j);
}

}

}
in.close();

}
 
Technology news on Phys.org
No one knows?
 
Nusc said:
No one knows?

Put it in a loop?

Code:
char c='y';
while(c!='n')
{

\\ Code here

cout<<"Do you wish to open another file (y/n)?"<<endl;
cin>>c;

}
 
I got it don't worry about it.

Thanks
 

Similar threads

  • · Replies 6 ·
Replies
6
Views
12K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 8 ·
Replies
8
Views
5K
Replies
12
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 4 ·
Replies
4
Views
6K
Replies
10
Views
2K
  • · Replies 8 ·
Replies
8
Views
6K
  • · Replies 12 ·
Replies
12
Views
2K
Replies
12
Views
3K