为什么通过添加字符串文字和char初始化时,为什么不打印字符串
Why is string not getting printed when being initialized by adding string literal and a char
在情况1中,输出为空白当我初始化这样的字符串时:
#include <iostream>
#include<string>
using namespace std;
//CODE 1
int main()
{
string s="hello" + 'c';
cout<<s<<endl;
return 0;
}
但是当我以这种方式写作时,它可以正常工作:
#include <iostream>
#include<string>
using namespace std;
//CODE 2
int main()
{
string s="hello";
char k='c';
s+=k;
cout<<s<<endl;
return 0;
}
现在,我很困惑,就像在堆栈溢出上问的另一个问题中,它说 namepace std 使用了字符串和std :: string之间没有区别> -> String和STD :: String之间没有功能差异,因为它们是相同的类型std :: string vs string在C 中而为此问题提供的答案指向差异:
编译器是G (GCC)4.8.5 20150623(红帽4.8.5-4)
有
string s="hello" + 'c';
等于
string s=("hello" + 'c');
ASCII编码与
相同string s=("hello" + 99);
与
相同string s=(&"hello"[99]);
也就是说,您得到了字符串"hello"
的100个元素的指针,该元素只有六个元素(不要忘记终结者)。
超出范围导致不确定的行为。
,因为 "string"
不是 std::string
,而是 const char*
,而指针加上一个数字(字符为"仅"数字)使用指针算术,因此添加后,您将获得const char*
,可能指向字符串字面之后的垃圾记忆。
第二个示例有效,因为在这种情况下,s
是 std::string
,它具有CHAN的operator +=
,并且> not 使用Pointer Arithmetic。
代码不同。在
中string s="hello" + 'c';
"hello"
不是std::string
。它是字符串文字,具有const char[N]
的类型。当您将字符添加到数组衰减到指针时,您正在执行指针算术。该算术正在超过字符串字面的末端,因此它是未定义的行为。
为了获得第一个代码,就像第二个示例一样,您需要将"hello"
作为字符串。您可以将用户定义的文字用于std::string
,例如
string s = "hello"s + 'c';
或仅使用构造函数
string s = std::string("hello") + 'c';
表达式 "hello" + 'c'
;正在将char
类型添加到const char[6]
类型中,并具有晦涩的结果。正式地,第一个参数腐烂到const char*
指针,并且使用指针算术算术的正常规则添加了c
。该行为可能是可能的未定义,因为我曾经遇到过的c
的数字值是所有编码,一个大于6的值,因此您最终试图尝试索引 const char
阵列"hello"
。
在第二版中,您将std::string
类的过载+=
运算符以char
为参数,并且字符c
是 conpateNated 到该字符串。
"hello" + 'c'
给出了"hello"
末端的指针(例如,假设ASCII字符集,'c'
具有数字值99
,并且"hello" + 99
给出了一个指向以前的99
字符的指针'h'
在"hello"
中)。
使用这样的指针来初始化std::string
提供了不确定的行为。
"代码2"工作std::string
具有接受char
的operator+=()
,并将其附加到字符串的末端。
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 用字符串初始化我的类的对象
- C++/Win32 构造函数不使用从对话框获取的字符串初始化变量
- 使用字符串初始化wchar_t[]
- 如何从常量字符串初始化 LPWSTR?
- 字符串初始化和打印
- 这是什么字符串初始化?
- 字符串初始化失败:"expression must have integral or unscoped enum type"
- 谁能告诉我如何用字符串初始化 ex 对象
- 函数原型中的字符串初始化
- 带双引号的字符串初始化
- C 字符串初始化会导致意外放置空字符
- 字符串初始化失败
- 将字符存储在用字符串初始化的字符指针中
- 为什么使用字符串初始化的C++位集是相反的
- 用c++中的字符串初始化char Buffer
- 带bool类型的字符串初始化
- c++字符串初始化
- 视觉 任何非(字符*)正确的方法,用于从 C++ 中的常量字符串初始化 void*