c++user-interfacec++-clifstream

I can't write a string variable to my file using fstream


When I click a button, I want a string value entered by a user to be stored in a file.

private: System::Void add_task_Click(System::Object^ sender, System::EventArgs^ e) {
        
    ofstream myFiles;
    myFiles.open("allTask.txt", fstream::out,fstream::app);
        
    String^ task_name = task->Text;
    
    tasks_list->Items->Add(task_name);
    if (myFiles.is_open()) {
        myFiles << task_name;
        myFiles.close();
    }
}

This does not work. What am I doing wrong?


Solution

  • You are mixing native C++ classes (like std::ofstream) with C++/CLI classes which are a part of .NET (like System::String). This will not work.

    You can solve it in one of the following 2 ways:

    1. Convert the C++/CLI String to native C++ std::string, and then write it to the std::ofstream:

      #include <msclr\marshal_cppstd.h>  // required for msclr::interop::marshal_as
      
      // ...
      
      std::string task_name_cpp = msclr::interop::marshal_as<std::string>(task_name);
      
      // ...
      
      myFiles << task_name_cpp;
      
    2. Use C++/CLI (i.e. .NET) file I/O and write task_name directly to it.
      You can see more info about .NET file I/O here: System::IO::File.

    Another issue is that you are not opening the std::ofstream correctly.
    Instead of:

    myFiles.open("allTask.txt", fstream::out,fstream::app);
    

    It should be:

    //---------------------------------------v--------------
    myFiles.open("allTask.txt", fstream::out | fstream::app);