为什么当我将数字添加到字符串时,它在c++中显示随机文本
Why when i add number to string it shows random text in c++?
当我尝试添加文本到字符串时,我得到随机值。
代码:#include <iostream>
using namespace std;
int main()
{
cout << "333" + 4;
}
我得到一些随机文本,如:↑←@
"333"
是const char [4]
而不是std::string
,因为您可能期望(顺便说一下,int
仍然没有operator+
)。添加4,将其转换为const char *
,然后将指针移动4 * sizeof(char)
字节,使其指向内存中的垃圾。
这是因为它们是两种不同的类型,并且加法运算符不像您期望的那样工作。
如果您打算将字符串字面值"333"与4的int值连接起来,那么您应该简单地使用count,如:
cout << "333" << 4; // outputs: 3334
如果要显示和,则使用stoi()
函数将string转换为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;
老实说,我不知道你想通过向string添加int来实现什么。如果您想要添加333+4,您需要像这样将string In解析为int:
编辑:错误# include
using namespace std;
int main()
{
cout << std::stoi("333") + 4;
}
相关文章:
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 指针没有更新它在void函数内部指向的值
- "assimp/config.h"找不到,但它在文件夹中
- 如何在 Mac 上正确编译C++,当它在 Linux 上编译没有问题时?
- 扩展类中的可选 vir 函数,测试它在运行时是否存在
- 我认为我的代码很好,但它在 cin a 之后停止并且没有进一步?
- EOF有更安全的替代方案吗?它在我的情况下不起作用
- 什么 /可以/ 你从一个函数返回. 并期望它在到达时还活着?
- 我的 SDL2 程序需要哪些二进制文件,以便它在另一台未安装 SDL2 的计算机中工作
- 它在 { 令牌之前给了我预期的标识符
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 请发现它在 dev 中工作的错误,但在 hackerrank 中不起作用
- 为什么它在不分配内存的情况下工作正常
- 文件追加的方式是,它在每次保存C++后结束行
- unqualified sort() -- 为什么它在 std::vector 上使用而不是在 std::array 上
- 为什么当我尝试从基本 clase 打印属性时,它在 c++ 中总是 0 ?
- 我不确定为什么代码没有运行,它在编译时抛出错误,说它无法找到 PrintArray()
- 当它在C++中内联功能时,谁来接受写入数字?
- 如何在 curl 代码C++设置授权持有者标头?我得到的授权不足,即使它在命令行上工作
- C++如何获取索引I处的元素,并检查它在向量或数组中是否为空