我想给一个字符串作为 Visual C++ 中 Stream Writer writeline 方法的参数
StreamWriter^ sw = gcnew StreamWriter("Positive Sample.txt");
string Loc = "blabla";
sw->WriteLine(Loc);
它生成错误 - 没有重载函数的实例与参数列表匹配
最佳答案
WriteLine
方法接受 CLI 的字符串,而不是 std 的字符串。
StreamWriter^ sw = gcnew StreamWriter("Positive Sample.txt");
String^ Loc = "blabla";
sw->WriteLine(Loc);
您可以使用System::Runtime::InteropServices::Marshal::PtrToStringAnsi
将C字符串编码为String
,或者您可以将C字符串传递到String的构造函数中:
string Loc = "blabla";
String^ strLoc = gcnew String(Loc.c_str());
编辑
正如 Ben 在评论中指出的那样,您应该使用 marshal_as
而不是 PtrToStringAnsi
:
// marshal_as_test.cpp
// compile with: /clr
#include <stdlib.h>
#include <string.h>
#include <msclr\marshal.h>
using namespace System;
using namespace msclr::interop;
int main() {
const char* message = "Test String to Marshal";
String^ result;
result = marshal_as<String^>( message );
return 0;
}
关于c++-cli - 给 StreamWriter 一个 std::string 来写入一个 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18377343/