2012-04-20 56 views
0

我寫了一個小型數獨程序,我想這樣做,所以每次按某個按鈕時,該按鈕上的文本都是前一個數字加1。所以,例如,我有一個大的按鈕,說「1」,我點擊它,它會說「2」,然後「3」,如果我再次點擊它,等到「9」。無法從std :: basic_string轉換爲int Visual Studio C++

起初我認爲它會非常簡單,我用這個代碼來調用一個整數,計數爲9,一個字符串等於按鈕文本,然後我試圖將int轉換爲字符串,我失敗了,它給了我錯誤波紋管。這是代碼:

int s = 0; 
String^ mystr = a0->Text; 
std::stringstream out; 
out << s; 
s = out.str(); //this is the error apparently. 
s++; 

這是錯誤:

error C2440: '=' : cannot convert from 'std::basic_string<_Elem,_Traits,_Ax>' to 'int'

我嘗試了這個錯誤在MSDN上搜索,但它比我的不同,和我離開的頁面比當我進入更困惑它。

另外供參考,我在Windows XP中使用Visual Studio 2010 C++中的Windows窗體應用程序。

+0

你試圖分配一個字符串爲整數,並期待它的工作?另外,C++/CLI不是C++。 – Praetorian 2012-04-20 16:25:23

回答

0

s類型爲intstr()返回string。你不能給int分配一個字符串。使用不同的變量來存儲字符串。

下面是一些可能的代碼。如果你想使用std::stringstream轉換std::stringchar*int(儘管它不會編譯)

string text = GetButtonText(); //get button text 
stringstream ss (text); //create stringstream based on that 
int s; 
ss >> s; //format string as int and store into s 
++s; //increment 
ss << s; //store back into stringstream 
text = ss.str(); //get string of that 
SetButtonText (text); //set button text to the string 
+0

但我想我把字符串轉換爲字符串,你有任何替代品將其轉換爲字符串? – Bugster 2012-04-20 16:24:25

+1

它讀入's',並且可以選擇以字符串形式返回's'。它實際上並沒有改變''的類型。使用'string'類型的變量來存儲結果。 – chris 2012-04-20 16:25:24

+0

您可以發佈我需要在您的文章中做的更改嗎? – Bugster 2012-04-20 16:27:32

3

,它看起來是這樣的:

int s = 0; 
std::string myStr("7"); 
std::stringstream out; 
out << myStr; 
out >> s; 

或者您可以直接使用myStr構建此stringstream,得到相同的結果:

std::stringstream out(myStr); 
out >> s; 

如果你想System::String^轉換爲std::string,它看起來是這樣的:

#include <msclr\marshal_cppstd.h> 
... 
System::String^ clrString = "7"; 
std::string myStr = msclr::interop::marshal_as<std::string>(clrString); 

雖然作爲Ben Voigt曾指出:當你開始System::String^,你應該把它通過使用一些功能轉換而不是.NET Framework。它也可能是這樣的:

System::String^ clrString = "7"; 
int i = System::Int32::Parse(clrString); 
+0

嘗試第一種方法時,我得到一個錯誤,說:「找不到操作符找到類型爲'System :: string ^'的右側操作數' – Bugster 2012-04-20 16:34:04

0

有很多的方式將字符串轉換爲int在C++ --the現代成語可能是安裝Boost庫和使用boost :: lexical_cast的。

但是,您的問題表明您對C++沒有很好的掌握。如果您的努力點是要學習更多關於C++的知識,那麼在嘗試像數獨這樣複雜的東西之前,您可能需要嘗試使用更簡單的教程之一。

如果你只是想用Windows窗體構建一個數獨遊戲,我建議你放棄C++,看看C#或VB.Net,這對缺乏經驗的程序員來說,缺陷少得多。

+0

其實我試圖將int轉換爲字符串,我確實沒有經驗寫C++桌面應用程序,但你在編碼時學得最好,這就是爲什麼我奮鬥 – Bugster 2012-04-20 16:32:44

2

既然你已經從String^,你想要的東西,如:

int i; 
if (System::Int32::TryParse(a0->Text, i)) { 
    ++i; 
    a0->Text = i.ToString(); 
} 
+0

+ 1通過使用.NET Framework的功能來轉換它。更好的解決方案:) – LihO 2012-04-20 22:17:48

相關問題