将文件名转换为c字符串

Converting the name of a file into a c-string

本文关键字:字符串 转换 文件名      更新时间:2023-10-16

我正试图打开一个.dat文件作为程序的输入。作业中说,我需要将为文件名输入的名称转换为c-string数据类型,以便可以通过.open(")命令读取。我的程序正在编译,但当我尝试转换文件名时,我确信我做错了什么。我四处寻找有类似问题的人,但我运气不好,所以如果你能给我任何建议,我将不胜感激!

这是我尝试打开文件的函数,以及我尝试转换文件名的另一个函数。

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 filen";
      exit (1);
    }
}
cout <<" Enter the name of the file: ";
cin>>filename;
convert(fp, filename);
fp.open("filename");

可能是(在目前支持C++11的情况下):

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

或(在C++03中):

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

旁注:数组中的元素从0索引到SIZE - 1,因此当您声明:时

float pay[SIZE];

然后当你这样做时:

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

您正在访问内存"传递"最后一个元素,这将导致未定义的行为