在字符串中使用空字符(C ++) [英] Use of null character in strings (C++)

查看:312
本文介绍了在字符串中使用空字符(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在刷我的C ++,偶然发现了关于字符串,字符数组和空字符('\0')的奇怪行为.以下代码:

I am brushing up on my C++ and stumbled across a curious behavior in regards to strings, character arrays, and the null character ('\0'). The following code:

#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;
}

产生输出:

> t
> t
>

幕后发生了什么?为什么字符串文字和声明的char数组将't'存储在索引6(在内部'\0'之后),但声明的字符串却不存储?

What is going on behind the scenes? Why does the string literal and the declared char array store the 't' at index 6 (after the internal '\0'), but the declared string does not?

推荐答案

据我所知,前两个本质上只是一个数组,打印字符串的方式是继续打印直到遇到\0 .因此,在前两个示例中,您从字符串中第6个字符的点偏移开始,但是在您的情况下,您将打印出第6个字符t.

From what I remember, the first two are in essence just an array and the way a string is printed is to continue to print until a \0 is encounterd. Thus in the first two examples you start at the point offset of the 6th character in the string, but in your case you are printing out the 6th character which is t.

string类发生的事情是,它将字符串的副本复制到其自己的内部缓冲区中,并且通过将字符串从数组的开始复制到找到的第一个\0来进行复制.因此t不会存储,因为它在第一个\0之后.

What happens with the string class is that it makes a copy of the string into it's own internal buffer and does so by copying the string from the start of the array up to the first \0 it finds. Thus the t is not stored because it comes after the first \0.

这篇关于在字符串中使用空字符(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆