I have a program in C++/CLI. I need to write my text and variable to file.
My code:
String^ MyVariable;
MyVariable = folderBrowserDialog1->SelectedPath // C://User/Users
std::ofstream out;
out.open("hello.txt");
if (out.is_open())
{
out << "Variable: " << MyVariable << std::endl; // ERROR
}
out.close();
How to fix error?
C++/CLI is a different language than C++.
It actually belong to the .NET family of languages and is meant to bridge .NET to native c++ code.
You cannot use
std::ofstream(which is a native C++ class) directly withSystem::String(which is a C++/CLI i.e. .NET class).You have 2 options:
Convert the
System::String(.NET) tostd::string(native C++). This is demonstrated here. After the conversion you can write it to the file usingstd::ofstreamas you attempted.Use .NET APIs for writing the file, for example with
FileStreamandStreamWriter, as demonstrated below:The content of the file will be: