无法从 std::basic_string 转换为 int Visual Studio C++

cannot convert from std::basic_string to int Visual studio C++

本文关键字:int Visual C++ Studio 转换 std basic string      更新时间:2023-10-16

我写了一个小型数独程序,我想让它成为每次按下某个按钮时,该按钮上的文本都是前一个数字递增一。

因此,例如,我

有一个大按钮,上面写着"1",我单击它,如果我再次单击它,它会说"2"然后"3",依此类推直到"9"。

起初我认为这很简单,我用这段代码调用了一个计数为 9 的整数,一个等于按钮文本的字符串,然后我尝试将 int 转换为字符串,但我失败了,它给了我错误下面。这是代码:

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

这是错误:

错误 C2440:"=":无法从"std::basic_string<_Elem,_Traits,_Ax>"转换为"int"

尝试在MSDN上搜索该错误,但它与我的不同,并且我离开页面时比输入时更困惑。

另外作为参考,我在Windows XP中使用Windows Forms应用程序,在Visual Studio 2010 C++中。

如果要使用 std::stringstreamstd::stringchar*转换为int,它可能看起来像这样:

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 <msclrmarshal_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);

由于您是从 String^ 开始的,因此您需要类似以下内容:

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

方法可以在C++中将字符串转换为 int --现代习语可能是安装 boost 库并使用 boost::lexical_cast。

但是,您的问题表明您对C++没有很好的把握。 如果您努力的目的是了解有关C++的更多信息,那么在尝试像数独这样复杂的东西之前,您可能想尝试许多更简单的教程之一。

如果你只是想用Windows窗体构建一个数独,我建议你放弃C++,看看C#或 VB.Net,对于没有经验的程序员来说,它们的陷阱要少得多。

s 的类型为 intstr()返回一个string。不能将字符串分配给 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
相关文章: