在C++中,11 basic_string::c_str被定义为完全相同basic_string::data,而后者又定义为*(begin() + n)和*(&*begin() + n)(when 0 <= n < size())完全相同.
我找不到任何要求字符串在其末尾始终具有空字符的内容.
这是否意味着c_str()不再保证生成以null结尾的字符串?
下面的字符串是否包含空终止符'\ 0'?
std::string temp = "hello whats up";
Run Code Online (Sandbox Code Playgroud)
谢谢!:)
对于常规C字符串,空字符'\0'表示数据的结尾.
那么std::string,我可以使用嵌入空字符的字符串吗?
以长度为前缀的字符串克服的零终止字符串有什么问题?
我正在读这本书写的Great Code vol.1我想到了这个问题.
在C++ 参考的c_str()在std::string出现以下:
返回值
指向基础字符存储的指针.
data()[i] == operator[](i) for every i in [0, size())(直到C++ 11)
data() + i == &operator[](i) for every i in [0, size()](自C++ 11起)
我不明白两者之间的区别,除了自C++ 11以来一个元素的范围增加.
前一种说法data()[i] == operator[](i)对后者来说也不正确吗?
§21.4.5 [string.access]
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
Run Code Online (Sandbox Code Playgroud)
返回:
*(begin() + pos)ifpos < size().否则,返回对charT具有value 的类型对象的引用charT(),其中修改对象会导致未定义的行为.
对我来说,第二部分意味着这个"类型对象charT"可能存在于存储在std::string对象中的序列之外.符合性的示例实现operator[]:
reference operator[](size_type pos){
static contexpr charT default = charT();
if(pos == size())
return default;
return buf[pos];
}
Run Code Online (Sandbox Code Playgroud)
现在,c_str()/ data(),按以下方式指定operator[]:
§21.4.7 [string.accessors]
const charT* c_str() const noexcept;
const charT* data() const noexcept;
Run Code Online (Sandbox Code Playgroud)
返回:一个指针
p,p + i == &operator[](i)用于每个iin[0,size()]. …
我正在刷我的C++,偶然发现了一个关于字符串,字符数组和空字符('\0')的奇怪行为.以下代码:
#include <iostream>
using namespace std;
int main() {
cout << "hello\0there"[6] << endl;
char word [] = "hello\0there";
cout << word[6] << endl;
string word2 = "hello\0there";
cout << word2[6] << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产生输出:
> t
> t
>
Run Code Online (Sandbox Code Playgroud)
幕后发生了什么?为什么字符串文字和声明的char数组存储't'at索引6(在内部之后'\0'),但声明的字符串不存在?
我们都知道自动附加到C字符串末尾的空字符... C++字符串对象怎么样?它的末尾是否还有一个空字符?
非常感谢!
谷歌搜索一段时间之后我不太确定的一件事是返回的getline()字符串.希望在这里得到确认.
std::getline
Run Code Online (Sandbox Code Playgroud)
这个全局版本返回一个std :: string,因此它不一定是以null结尾的.有些编译器可能附加'\ 0'而其他编译器则不会.
std::istream::getline
Run Code Online (Sandbox Code Playgroud)
此函数返回一个c样式的字符串,因此可以保证字符串以空值终止.
是对的吗?