0

How would you go about giving the user the ability to change the Name of the ofstream File using c++ MFC. I would like to add an Edit Control Box that will give the user an ability to Type in the File Name before clicking save. This is my current code, any feedback will be greatly appreciated.

void CECET_MFC_Dialog_Based_IntroDlg::OnBnClickedSave()
    {
    UpdateData(true);

    ofstream myfile ("Save_Random.xls");
    if (myfile.is_open())
  {
    myfile << "This is the 1st line.\n" << endl;

    for(int index=0; index<100; index++){   // samples to create
     myfile << setprecision(4) << dblArray[index] << endl;
    }

    myfile << "This is another line.\n";
    myfile << "Max  = " << rndMax << endl;
    myfile << "Min  = " << rndMin << endl;
    myfile << "Mean = " << Final_Avg << endl;
    myfile.close();
  }
    else cout << "Unable to open file";

    UpdateData(false);  
}
4

1 回答 1

1

您可以像添加任何其他控件一样添加编辑控件——将其从工具箱拖到对话框中。也许更重要的是,您通常希望在它旁边放置一个浏览按钮,以便用户可以浏览他们想要的文件夹/文件名。该按钮的代码如下所示:

void CYourDlg::OnBrowseButton() {
    UpdateData();

    CFileDialog dlg(false, NULL, NULL, OFN_OVERWRITEPROMPT );

    if (dlg.DoModal())
        m_dest_file = dlg.GetPathName();
    UpdateData(false);
}

然后,当用户单击任何按钮(或菜单项等)让您写入文件时,您会执行以下操作:

std::ofstream myfile(m_dest_file);
// write the data

我假设您已将编辑控件与CString命名的m_dest_file. 显然,您可以选择自己喜欢的名称,但是(当然)您需要在两个地方使用相同的名称。

于 2013-04-21T23:11:03.327 回答