【发布时间】:2016-11-03 12:18:45
【问题描述】:
当我尝试将文本添加到字符串时,我得到随机值。
代码:
#include <iostream>
using namespace std;
int main()
{
cout << "333" + 4;
}
我收到一些随机文本,例如:↑←@
【问题讨论】:
-
我只是好奇:你到底希望得到什么?
当我尝试将文本添加到字符串时,我得到随机值。
代码:
#include <iostream>
using namespace std;
int main()
{
cout << "333" + 4;
}
我收到一些随机文本,例如:↑←@
【问题讨论】:
"333" 是 const char [4] 而不是 std::string,正如您所期望的(顺便说一下,operator+ 仍然没有 int)。加 4,您将 converting 移动到 const char *,然后将指针移动 4 * sizeof(char) 字节,使其指向包含垃圾的内存。
【讨论】:
发生这种情况是因为它们是两种不同的类型,并且加法运算符无法按您预期的那样工作。
如果您打算将字符串文字 "333" 与 int 值 4 连接,那么您应该简单地使用 count 如下:
cout << "333" << 4; // outputs: 3334
如果您想显示 sum,请使用 stoi() 函数将字符串转换为 int。
cout << stoi("333") + 4; // outputs: 337
注意: 使用 stoi() 时:如果字符串还包含文字,则转换将从字符串的开头获取整数值,或者如果字符串以文字:
cout << stoi("333ab3") + 4; // same as 333 + 4, ignoring the rest, starting a
cout << stoi("aa333aa3") + 4; // raise error as "aa" can't be casted to int
【讨论】:
当您想在文本中添加文本时,解决方案是使用适当的类型:
cout << std::string( "333" ) + "4";
对于 c++14 或更高版本:
using namespace std::string_literals;
cout << "333"s + "4"s;
【讨论】:
老实说,我不知道您通过将 int 添加到字符串来达到什么目的。如果要添加 333+4,则需要像这样将字符串解析为 int:
编辑:错字 #包括
using namespace std;
int main()
{
cout << std::stoi("333") + 4;
}
【讨论】:
using namespace std;,这不会编译。