我有一个 C++ 程序。我需要显示我的文本和变量。 我的代码:
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();
如何修复错误?
c++/cli 是一种与 c++ 不同的语言。
它实际上属于 .NET 语言家族,旨在将 .NET 与本机 C++ 代码联系起来。
您不能直接将
std::ofstream
(这是一个本机 C++ 类)与 System::String
(这是一个 C++/cli 类)一起使用。
您有 2 个选择:
将
System::String
转换为 std::string
。 here 对此进行了演示。
使用 .NET API 写入文件,例如使用
FileStream
和 StreamWriter
,如下所示:
System::String^ MyVariable = gcnew System::String("abc");
System::IO::FileStream^ fs = System::IO::File::Create("hello.txt");
System::IO::StreamWriter^ sw = gcnew System::IO::StreamWriter(fs);
sw->WriteLine("Variable: " + MyVariable);
sw->Close();
影片内容为:
Variable: abc