首页 > 解决方案 > 如何在不编组的情况下将 System::String 转换为 std::string?

问题描述

互联网上的每一篇文章都告诉我使用编组。问题是编组在我的 Windows 窗体应用程序上不起作用。该库与 Windows 表单或类似“歧义符号”之类的东西发生冲突,我已经尝试将它们放在不同的名称空间中,我已经尝试在不同的 cpp 文件上声明名称空间,但它不起作用。我正在开发一个 Windows 窗体应用程序,我需要使用 fstream 将数据保存在 txt 中,但我需要 std::string 上的数据,否则 fstream 不会读取它。但无论出于何种原因,Windows 窗体只会强制您使用它们的托管类,即 String^。有谁知道我可以完成这项任务的方法吗?拜托,我会很感激的。

我的标题

#include "NewProject.h"
#include <fstream>
#include <msclr\marshal_cppstd.h> 

这是我的加载方法

    private: System::Void Interf_Load(System::Object^  sender, System::EventArgs^  e) {
    ifstream infile;
    bool fresh_start = false;
    infile.open("Data.txt", ios::binary);

    if (infile.fail()) {
        fresh_start = true;
        infile.close();
    }

    if (!fresh_start) {
        size_t index; infile >> index;
        for (size_t i = 0; i < index; i++) {
            string* temp = new string[5];

            for (size_t j = 0; j < 5; j++) {
                infile >> temp[j];
            }
            String^ p1 = gcnew String(temp[0].c_str()); String^ p2 = gcnew String(temp[1].c_str());
            String^ p3 = gcnew String(temp[2].c_str()); String^ p4 = gcnew String(temp[3].c_str());
            String^ p5 = gcnew String(temp[4].c_str()); int valor = int::Parse(p5);

            apu->proyectos.Add(gcnew Project(p1, p2, p3, p4, valor));

        }
    }

这是为了节省。

private: System::Void button8_Click(System::Object^  sender, System::EventArgs^  e) {

ofstream outfile;
outfile.open("Data.txt", ios::binary);
outfile << apu->proyectos.Count << "\n";

for (size_t i = 0; i < apu->proyectos.Count; i++) {

    std::string u1 = msclr::interop::marshal_as<std::string>(apu->proyectos[0]);
    std::string u2 = msclr::interop::marshal_as<std::string>(apu->proyectos[1]);
    std::string u3 = msclr::interop::marshal_as<std::string>(apu->proyectos[2]);
    std::string u4 = msclr::interop::marshal_as<std::string>(apu->proyectos[3]);
    std::string u5 = msclr::interop::marshal_as<std::string>(apu->proyectos[4]);

    std::string line(std::string(u1 + " " + u2 + " " + u3 + " " + u4 + " " + u5) + "\n");
    char* buffer = &line[0u];
    outfile.write(buffer, line.size());
}




Close();

}

然后我得到关于不明确符号的 1082 个错误。当我删除 Marshall 的东西时,我的应用程序运行良好,所以这是罪魁祸首。

标签: c++stringc++-clisystem

解决方案


推荐阅读