gpt4 book ai didi

c++-cli - 给 StreamWriter 一个 std::string 来写一个 txt 文件

转载 作者:行者123 更新时间:2023-12-04 04:44:41 24 4
gpt4 key购买 nike

我想给一个字符串作为 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 :

来自 here 的示例(逆运算可以找到 here )
// 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com