为什么当我将数字添加到字符串时,它在c++中显示随机文本

Why when i add number to string it shows random text in c++?

本文关键字:c++ 它在 显示 文本 随机 字符串 数字 添加 为什么      更新时间:2023-10-16

当我尝试添加文本到字符串时,我得到随机值。

代码:

#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;
}
相关文章: