将 System::String 转换为 Const Char *
我正在使用 Visual C++ 2008 的 GUI 创建器来制作用户界面。单击按钮时,将调用以下函数。内容应该创建一个文件,并以文本框“Textbox”的内容命名该文件,末尾带有“.txt”。但是,这导致我出现转换错误。以下是代码:
私有: System::Void Button_Click(System::Object^ 发送者,System::EventArgs^ e) { ofstream myfile(文本框->文本+“.txt”); myfile.close(); } 这是错误
:
错误 C2664: 'std::basic_ofstream<_Elem,_Traits>::basic_ofstream(const char *,std::ios_base::openmode,int)' : 无法将参数 1 从 'System::String ^' 转换为 '常量字符 *'
我怎样才能进行转换以允许它通过?
I am using Visual C++ 2008's GUI creator to make a user interface. When a button is clicked, the following function is called. The content is supposed to create a file and name the file after the contents of the textbox "Textbox' with '.txt' at the end. However, that leads me to a conversion error. Here is the code:
private: System::Void Button_Click(System::Object^ sender, System::EventArgs^ e) {
ofstream myfile (Textbox->Text + ".txt");
myfile.close();
}
Here is the error:
error C2664: 'std::basic_ofstream<_Elem,_Traits>::basic_ofstream(const char *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'System::String ^' to 'const char *'
How can I do a conversion to allow this to go through?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
很简单!
当您使用托管 C++ 时,请使用 include 并进行如下操作:
It's simple!
As you're using managed C++, use the include and operate like:
我会使用编组:
但请注意,您随后仅使用 Ansi 字符串。如果您需要 unicode 支持,可以使用 Widechar STL 类
wofstream
和PtrToStringChars
(#include
) 从 <代码>系统::字符串。在这种情况下,您不需要释放固定的指针。I would use marshalling:
But note that you then use just Ansi strings. If you need unicode support you can use the widechar STL class
wofstream
andPtrToStringChars
(#include <vcclr.h>
) to convert fromSystem::String
. In that case you do not need to free the pinned pointer.谢谢杰德汉。我几乎没有修改代码以将其与我的“正常”System::String 一起使用。
如果你想转换 System:String -> 这是这样的方式标准:字符串。
Thanks jdehaan. I little modified the code to use it with my 'normal' System::String's.
This is the way if you want to convert System:String -> std:string.
您可以将其转换为 CString,然后向其添加扩展名。
有一个内置的 CString 构造函数将允许进行此转换
示例:
在您的具体情况下:
You can convert it to a CString and then add the extension to it.
There is a built-in CString constructor which will allow this conversion to happen
Example:
In your specific case:
MSDN 中有一篇关于字符串转换的非常优秀的文章:
http://msdn.microsoft.com/en-us/library/ms235631%28vs.80%29.aspx
有许多示例可以将 String 与不同类型相互转换。
There is an really excellent article in MSDN about String conversions here:
http://msdn.microsoft.com/en-us/library/ms235631%28vs.80%29.aspx
There are many samples to convert String from and to different types.