【问题标题】:cannot convert from std::basic_string to int Visual studio C++无法从 std::basic_string 转换为 int Visual Studio C++
【发布时间】:2012-04-20 16:19:29
【问题描述】:

我已经编写了一个小型数独程序,我想制作它,这样每次你按下某个按钮时,该按钮上的文本就是之前的数字加一。

例如,我有一个大按钮,上面写着“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>”转换为“int”

我尝试在 MSDN 上搜索该错误,但它与我的不同,而且我留下的页面比我输入它时更加混乱。

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

【问题讨论】:

  • 您正在尝试将字符串分配给整数并期望它能够工作?此外,C++/CLI 不是 C++。

标签: c++ visual-studio-2010 visual-c++ c++-cli type-conversion


【解决方案1】:

如果您想使用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 <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);

【讨论】:

  • 在尝试第一种方法时,我收到一条错误消息“未找到采用'System::string^'类型的右手操作数的运算符
【解决方案2】:

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

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

【讨论】:

  • +1 用于使用 .NET Framework 中的函数进行转换。更好的解决方案:)
【解决方案3】:

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

但是,您的问题表明您对 C++ 没有很好的掌握。如果您的目标是学习更多关于 C++ 的知识,那么在尝试像数独这样复杂的东西之前,您可能想先尝试许多更简单的教程之一。

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

【讨论】:

  • 实际上我正在尝试将 int 转换为字符串。我在编写 C++ 桌面应用程序方面确实缺乏经验,但你在编码时学得最好,所以这就是我苦苦挣扎的原因
【解决方案4】:

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

【讨论】:

  • 但我以为我将 s 转换为字符串,您有其他方法可以将其转换为字符串吗?
  • 它读入s,并且可以选择以字符串形式返回s。它实际上并没有改变s 的类型。使用string 类型的变量来存储结果。
  • 您能否在您的帖子中发布我需要做的更改?
猜你喜欢
  • 2017-03-10
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2015-07-23
  • 2015-01-03
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
相关资源
最近更新 更多