Question

I am trying to open a .dat file to use as an input for my program. The assignment says I need to convert the name I enter for the file name into c-string datatype so it can be read through the .open("") command. My program compiles but I'm sure I'm doing something wrong when I try to convert file name. I have looked around for people with similar problems but I've had no luck so any suggestions you can give me would be much appreciated!

Here is the function where I attempt to open the file, and the other function where I try to convert the file name.

int main()
{
  ifstream fp;
  string name[SIZE], filename;
  int counter, idx = 0;
  float rate[SIZE], sum[SIZE], gross[SIZE], with[SIZE], pay[SIZE], net[SIZE], hours[SIZE];
  getfile(fp, filename);
  readFile(fp, name, rate, hours);
  pay[SIZE] = calcPay(rate, sum);
  gross[SIZE] = calcGross(pay);
  with[SIZE] = calcAmount(gross);
  net[SIZE] = calcNet(gross, with);
  output(name, rate, sum, with, gross, net, pay, SIZE);
  return 0;
}

//Convert filename into C-string                                                                    
string convert(ifstream &fp, string filename)
{
  fp.open(filename.c_str());
  return filename;
}

//Get file name from user.                                                                          
void getfile(ifstream &fp, string filename)
{
  cout <<" Enter the name of the file: ";
  cin>>filename;
  convert(fp, filename);
  fp.open("filename");
  if (!fp)
    {
      cout<<"Error opening file\n";
      exit (1);
    }
}
Was it helpful?

Solution

cout <<" Enter the name of the file: ";
cin>>filename;
convert(fp, filename);
fp.open("filename");

was probably meant to be (in case of present C++11 support):

cout << " Enter the name of the file: ";
cin >> filename;
fp.open(filename);

or (in C++03):

cout << " Enter the name of the file: ";
cin >> filename;
fp.open(filename.c_str());

Side note: Elements in an array are indexed from 0 to SIZE - 1 so when you declare:

float pay[SIZE];

then when you do:

pay[SIZE] = calcPay(rate, sum);

you are accessing memory "pass" the last element, which causes undefined behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top