我是C ++的新手。我正在尝试用C ++编写程序,但是当我使用e.what()
时出现错误。我已经包含了#include <exception>
,但我得到了error C2664 - Cannot convert parameter 1 from const char* to system::string ^
。
这是代码。
#pragma once
#include <iostream>
#include <fstream>
#include <exception>
#include <string>
namespace SilverthorneTechnologiesSchoolDashboard {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace std;
//Form parameters
#pragma endregion
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
ifstream codeFile;
try{
codeFile.open("userDetails.info");
}
catch (exception &e)
{
label1->Text = e.what();
}
}
};
}
答案 0 :(得分:2)
codeFile
是非托管代码,抛出非托管异常,因此您正在正常捕获异常。您只需将const char *
转换为String^
即可将其放入用户界面。
String类有一个构造函数,它带有char*
(char *是C#中的SByte *)。 label1->Text = gcnew String(e.what());
应该可以解决您的问题。
也就是说,您可以使用托管流对象。这将为您提供托管异常,而不是非托管,并且与托管代码的其余部分具有更强的互操作性。看看FileStream,看看它是否符合您的需求。
答案 1 :(得分:-1)
这是一个猜测但尝试改变
catch (exception &e)
到
catch (exception& e)