无法从 std::basic_string 转换为 int Visual Studio C++
cannot convert from std::basic_string to int Visual studio C++
我写了一个小型数独程序,我想让它成为每次按下某个按钮时,该按钮上的文本都是前一个数字递增一。
因此,例如,我有一个大按钮,上面写着"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::stringstream
将std::string
或char*
转换为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 的类型为 int
。 str()
返回一个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
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 定义 uint= "unsigned int" 没有像我在 Visual Studio 中使用 nvcc 时预期的那样应用
- 为什么我不能使用在 Visual C++ 32 位中实现运算符无符号 int() 作为数组索引的类?
- Visual studio 2013 和 g++ 7.1 中将 int 和 long 类型相乘时的 c++ 差异行为
- Visual Studio 不采用 array: int magicSquare[n][n]?
- Visual C 计算器类让我在多个CPP文件上传播最低的INT
- 在C++/Visual Studio中,通过给定数据格式(doubles、float、int、1位bools)的UDP发
- C - Visual Studio-缺少类型的指定词 - 假设INT
- Visual Studio调试与发布版本:比较int和float不匹配
- 在c++中将字符串转换为int,得到更小的值Visual Studio 2013
- visual Int to char c++
- visual x86-64 MSVC++/Intel C++更改int、long等的大小
- 为什么Visual Studio在自我分配时不触发警告(int foo = foo;)
- C++和Visual Studio错误 - 不存在从"std::basic_ostream<char, std::char_traits<char>>"到"int"的合适转换功
- 无法从 std::basic_string 转换为 int Visual Studio C++
- 为什么Visual Studio没有将无符号值显示为int?
- 在Visual Studio 2015社区C ++中,如何修复警告C4838:从'unsigned int'到'int'的转换需要缩小转换范围
- visual C++缺少类型说明符-假定为int
- 为什么在visual studio中连续的int数据类型变量位于12个字节的偏移
- Visual Studio 2008下使用long long int的编译器错误的原因是什么?