2016-05-31 45 views
-2

你好我想在Visual Studio 2013上使用Windows應用程序窗體做一個C++登錄界面。問題是,我試圖比較文本框中的值與文件中的行,但我出現操作數類型不兼容的錯誤。使用Windows應用程序的C++登錄界面

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { 
     string un, pw; 

     ifstream read("file.txt"); 
     getline(read, un); 
     getline(read, pw); 


     if (textBox1->Text = un && textBox2->Text = pw){ 

      MessageBox::Show("You have successfully login!", "Login Message", MessageBoxButtons::OK, MessageBoxIcon::Information); 

     } 

     else { 
      MessageBox::Show("Incorrect Password or Username !", "Login Message", MessageBoxButtons::OK, MessageBoxIcon::Error); 
        } 

     read.close(); 


    } 
+2

如果你不擅長C++並且不想學習這門語言,爲什麼要在其中編寫代碼? – SergeyA

+2

如果你有編譯錯誤,你應該分享它們。發生錯誤是不好的。 – NathanOliver

+0

@NathanOliver,想分享一下我的? :) – SergeyA

回答

0

兩者是錯在這裏:

if (textBox1->Text = un && textBox2->Text = pw){ 

問題1:unstd::string,a C++ standard library stringtextBox1->TextSystem::String ^,指向a .Net string的託管指針。

這些類型是非常不同的,並不是(自動)可比較的。你需要將一個轉換爲另一個來比較它們。鑑於將System::String轉換爲std::string比其他方式通常要煩惱得多,因爲System::String是一個局部化的,基於字符的寬字符串,讓我們沿着阻力最小的路徑走。

if (textBox1->Text = gcnew String(un.c_str()) && textBox2->Text = gcnew String(pw.c_str())){ 

現在值是相同的類型,System::String。這暴露了問題2.

問題2:=是賦值運算符。這目前試圖分配untextBox1->Text,而不是比較。你的意思是寫:

if (textBox1->Text == gcnew String(un.c_str()) && textBox2->Text == gcnew String(pw.c_str())){ 
0

在C++中,您的賦值運算符是'=',您的比較運算符是'=='。

你會想你的代碼更改爲:如果(textBox1->文本==未& & textBox2->文本== PW)

+0

錯誤仍然是一樣的。哪些是操作數類型不兼容(「System :: String ^」和「std :: string」) – Lily

+0

這是因爲它們*是*不同類型。 [你在混合使用C++和CLI](https://en.wikipedia.org/wiki/C%2B%2B/CLI)數據類型。這個答案可能會有所幫助:http://stackoverflow.com/questions/13718188/convert-from-stdstring-to-string或直接從馬的嘴巴:https://msdn.microsoft.com/en-us/library/ms235219 .aspx – user4581301

+0

謝謝!它幫助! – Lily