性病的每个字符地址::字符串 [英] Address of each character of std::string

查看:128
本文介绍了性病的每个字符地址::字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图打印性病的每个字符:: string的的地址。但我呆在一起理解什么与内部发生的std ::字符串而对于数组这是给的地址如我所料是造成此输出。可能有人请解释一下到底是怎么回事?

 的#include<&iostream的GT;
#包括LT&;串GT;使用命名空间std;诠释主(){   字符串str =你好;
   诠释一个[] = {1,2,3,4,5};   的for(int i = 0; I< str.length(); ++ I)
      COUT<< &放大器;海峡[1] - ;&下; ENDL;   COUT<< **************<< ENDL;   对(INT I = 0; I&小于5 ++ⅰ)
      COUT<< &放大器;一[1] - ;&下; ENDL;    返回0;
}

输出:

 你好
ELLO
LLO

Ø
**************
0x7fff5fbff950
0x7fff5fbff954
0x7fff5fbff958
0x7fff5fbff95c
0x7fff5fbff960


解决方案

的std :: ostream的试图打印的char * 它假定它是一个C风格的字符串。

其转换为无效* 打印前,你会得到你所期望的:

  COUT<< (无效*)及海峡[1]  - ;&下; ENDL;

I tried to print the address of each character of std::string. But I amn't understanding what is happening internally with std::string that is resulting this output while for the array it is giving the address as I expected. Could someone please explain what is going on?

#include <iostream>
#include <string>

using namespace std;

int main(){

   string str = "Hello";
   int a[] = {1,2,3,4,5};

   for( int i=0; i<str.length(); ++i )
      cout << &str[i] << endl;

   cout << "**************" << endl;

   for( int i=0; i<5; ++i )
      cout << &a[i] << endl;

    return 0;
}

Output:

Hello
ello
llo
lo
o
**************
0x7fff5fbff950
0x7fff5fbff954
0x7fff5fbff958
0x7fff5fbff95c
0x7fff5fbff960

解决方案

When a std::ostream tries to print a char* it assumes it's a C-style string.

Cast it to a void* before printing and you will get what you expect:

cout << (void*) &str[i] << endl;

这篇关于性病的每个字符地址::字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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