2013-01-17 36 views
0

我是C++新手。我想用C++編寫一個程序,但是當我使用e.what()時出現錯誤。我已經包含#include <exception>,但我得到error C2664 - Cannot convert parameter 1 from const char* to system::string ^以C++形式捕獲異常

這是代碼。

#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(); 
     } 
     } 
}; 
} 
+3

這不是C++。 – aschepler

+2

您需要將此標記爲另一種語言,因爲它不是C++。 – juanchopanza

回答

2

codeFile是託管代碼,拋出異常的非託管,所以你正確地捕捉異常。您只需將const char *轉換爲String^即可將其放入您的用戶界面。

String類有一個構造函數,它需要一個char*(在C#中char *是SByte *)。 label1->Text = gcnew String(e.what());應該可以解決你的問題。

也就是說,您可以使用託管流對象。這將爲您提供受管理的異常,而不是非託管的,以及與其他託管代碼更好的互操作性。看看FileStream,看看是否符合你的需求。

-1

這是一個有點猜測,但嘗試改變

catch (exception &e) 

catch (exception& e) 
+0

不,對不起。它不起作用 –